区别
map
特点:内部实现一个红黑树(一种平衡二叉检索树),自动排序,map中所有元素都是有序的
优点:运行效率高,红黑树的检索效率要高于vector、队列、列表等;中序遍历可以得到有序序列,从外部操作来看只需要遍历map即可得到有序序列
缺点:树中每一个结点都需要保存:父结点、孩子结点、红/黑性质,这些信息会占用很大空间
适用于:对顺序有要求的问题
unoredered_map
特点:内部实现一个哈希表,排列无序
优点:由于是基于哈希表,所以查找速度非常快,可达到O(1)
缺点:哈希表建立耗时,遍历unoredered_map时,遍历顺序与插入顺序可能不同
适用于:查找问题
set
与map一样,内部同样实现红黑树,且中序遍历可以实现有序遍历
unordered_set
与unordered_map一样,内部同样实现哈希表,排列无序
使用
下面以unordered_map为例展示具体的操作
unordered_map(哈希表)的创建、插入、读取、判断、遍历等操作:
#include <unordered_map>
1.创建
unordered_map<type1, type2> map;
unordered_map<string, int> map = {{"A",1},{"B",2}}; //可以创建时初始化
//以<string, int>为例
string key = "A";
int value = 1;
2.大小
map.size();
3.插入
map.emplace(key, value); //key存在则不变
map[key] = value; //key存在则覆盖,只有这个会覆盖
map.insert(pair<string,int>(key,value)); //key存在则不变,使用pair插入
//拓展(pair):pair<string, int>(str,i) 声明一个pair对象
4.获取
int v = map["A"]; //注意:只要进行map[X]操作,如果map中有X,则返回其value,如果没有X,则会插入X,并赋值为0
5.遍历输出
for(auto x : map){
cout<<x.first<<" "<<x.second<<endl;
}
for(auto x: map){
cout<<map[x.first]<<endl;
}
for(unordered_map<string,int>::iterator it=map.begin();it!=map.end();it++)
cout<<"key: "<<it->first<<"value: "<< it->second<<endl;
6.判断key是否在map中
//count返回key出现的次数:如果没有,count返回0,有则返回1(因为unordered_map中不允许出现重复的元素)
map.count("B")!= 0
//find返回iterator:如果key存在,返回key对应的it,如果不存在,返回end。
map.find("B")!= map.end()
//切记,不要用map["B"]来判断:如果没有B,会返回0,但也会插入一个"B",值为0;
这一系列中(map、unordered_map、set、unordered_set)的操作都大同小异,差不太多。
map和unordered_map用法一样,提供insert、size、count等操作,元素也是按照pair来存储,两者区别在于底层实现原理不同,从外部使用来看,两者几乎一致(除了有序和无序、或效率等问题,只从外部操作上看两者一样)。
set和unordered_set的操作也与map和unordered_map类似,区别在于set中保存的不是键值对,而是单独的变量,除此之外,在创建和遍历时采取的操作会有细微的不同。
操作对比
1.创建
//set 和 unordered_set
set<int> set;
unordered_set<int> un_set;
//map 和 unordered_map
map<string, int> map;
unordered_map<string, int> un_map;
2.操作
//set、unordered_set、map、unordered_map的操作都几乎相同
// 提供size()/count()/find()/insert()等函数,且功能基本都一样
// 都有begin()/end()等迭代器操作
3.遍历
//set 和 unordered_set
for(set<int>::iterator iter=test_set.begin();iter!=test_set.end();iter++){
cout<<"value: "<<*iter<<endl;
}
//map 和 unordered_map
for(map<int,int>::iterator iter=test_map.begin();iter!=test_map.end();iter++){
cout<<"key is "<<iter->first<<"value is "<< iter->second<<endl;
}