把hash函数修改成inline处理一下,并且加了一个map函数key为char*的进行对比 源码 #include <string.h> #include <sstream> #include <list> #include <sys/time.h> #include <unordered_map> #include <cstdlib> #include <stdio.h> #include "unistd.h" #include <map> using namespace std; struct Cmp...
//使用const char*,key为10000000时:unorder_mapcharcreate cost11.7611unorder_mapcharfind cost1.55619unorder_map std::stringcreate cost13.5376unorder_map std::stringfind cost2.33906//使用struct c_string,key为10000000时:unorder_mapcharcreate cost7.35524unorder_mapcharfind cost1.60826unorder_map std::stringcre...
// 创建一个 unordered_map,键为 int,值为 string std::unordered_map<int, std::string>myMap; // 插入一些键值对 myMap[1]="one"; myMap[2]="two"; myMap[3]="three"; // 打印所有元素 for(constauto&pair:myMap){ std::cout<<"Key: "<<pair.first<<", Value: "<<pair.second<<std...
与类模板 unordered_multimap 类不同,unordered_map 类型的对象可确保 key_eq()(X, Y) 对于受控序列的任意两个元素始终为 false。 (键是唯一的。)此对象还存储最大加载因子,用于指定每个存储桶的元素的最大所需平均数量。 如果插入元素导致 unordered_map::load_factor() 超出最大加载因子,容器将增加存储桶的...
unordered_map和map类似,都是存储的key-value的值,可以通过key快速索引到value。不同的是unordered_map不会根据key的大小进行排序, 存储时是根据key的hash值判断元素是否相同,即unordered_map内部元素是无序的,而map中的元素是按照二叉搜索树存储,进行中序遍历会得到有序遍历。
for (unordered_map<string, double>::iterator it = hash.begin(); it != hash.end(); it ++ ) { cout << it->first << ' ' << it->second << endl; } 1. 2. 3. 4. 进阶操作 如果想让自定义的class作为key(unordered_map<key,value>)来使用unordered_map,需要实现: ...
NOTE:有如下结构体 library::book,你想用它作为 unordered_map 的 key 值,你需要做两件事:重载 == 和 定义 hash_value 函数。前者定义比较 key 值是否唯一,后者提供一个hash值,用于存储。 namespace library { struct book { int id; std::string author; std::string title; // ... }; bool oper...
unordered_map中的key使用string还是int效率更高? unordered_map对比python的dict性能差多少? unordered_map中的key使用string还是int效率更高? 先以24字节长度的字符串做key,生死10000个存在字典里面,然后在遍历查询10000000次,看最终消耗 #include<iostream>#include<string>#include<random>#include<unordered_map>#incl...
当key可以强转成整形时(比如负数,指针等),用缺省的仿函数即可。当key是string这种不能强转成整形的类型时,就要手动写一个转换成整形的仿函数。上方是取string的第一个字符进行返回。同时也要手动传入这个仿函数。 这种取首字符的方法不是很好,下面是另一种字符串哈希算法: ...
C++中map和unordered_map提供的是一种键值对容器,在实际开发中会经常用到,它跟Python的字典很类似,所有的数据都是成对出现的,每一对中的第一个值称之为关键字(key),每个关键字只能在map中出现一次;第二个称之为该关键字的对应值(value)。 map和unordered_map map是一种有序的容器,底层是用...