一、内容描述
本文记录了map/unordered_map的几种遍历方式,使用新的C++语法让map/unordered_map的遍历变得简单。
二、实现方案
以unordered_map
为例,map
同理,只需要将以下代码部分的unordered_map
修改为map
即可,实现代码如下:
//map unordered_map 遍历
#include<iostream>
#include<algorithm>
#include<unordered_map>
using namespace std;
int main(){
unordered_map<char, int> hashmap;
hashmap['a'] = 1;
hashmap.insert(pair<char, int>('b',2));
hashmap['c'] = 3;
// 方式一
cout<<"方式1:"<<endl;
for(unordered_map<char,int>::iterator item = hashmap.begin(); item != hashmap.end(); item++){
cout<<item->first<<" "<<item->second<<endl;
}
// 方式二
cout<<"方式2:"<<endl;
for(auto item = hashmap.begin(); item != hashmap.end(); item++){
cout<<item->first<<" "<<item->second<<endl;
}
// 方式三
cout<<"方式3:"<<endl;
for(auto &item : hashmap){
cout<<item.first<<" "<<item.second<<endl;
}
return 0;
}
三、结果
方式1:
c 3
b 2
a 1
方式2:
c 3
b 2
a 1
方式3:
c 3
b 2
a 1
以下语句可以查看unordered_map中是否存在某个元素和对其进行访问。
auto it= hashmap.find('b');
if (it != hashmap.end() )
cout<< it ->first <<" "<< it ->second <<endl;
如果本文能给你带来帮助的话,点个赞鼓励一下作者吧!
四、map/unordered_map区别
这里简单对比一些map和unordered_map的区别。
特点 | map | unordered_map |
---|---|---|
底层实现 | 红黑树 | 哈希表 |
有序与否 | 元素有序 | 元素无序 |
优点 | 建立过程自动排序 | 查找速度快 |
缺点 | 查找速度慢 | 哈希表建立时间慢,内存占用大 |
适合领域 | 对顺序有要求的问题 | 对查找速度有要求的问题 |