map和unordered_map的遍历方法是相同的,不过遍历结果,map是有序的,unoredred_map遍历是无序的。 std:map 是个有序的关系容器,其完整原型如下:
template<
class Key,
class T,
class Compare=std::less<Key>,
class Allocator=std::allocator<std::pair<const Key,T>>
>class map;
键值对会根据键来用 Compare 排序,具体到 std::map<int, int> 就是:
map<int,int,std::less<int>>
C++11 map和unordered_map遍历方法
一、迭代器 iterator
for(map<int,int>::iterator it=mp.begin();it!=mp.end();++it)
cout<<it->first<<"--"<<it->second<<"\t";
for(map<int,int>::const_iterator it=mp.begin();it!=mp.end();++it)
cout<<it->first<<"--"<<it->second<<"\t";
二、类型萃取 (traits) value_type
for(map<int,int>::value_type& i:mp)
cout<<i.first<<"--"<<i.second<<"\t";
三、实际类型 pair
for(pair<const int ,int>&i:mp)//key必须是const的
cout<<i.first<<"--"<<i.second<<"\t";
四、结构化绑定 auto
for(auto&[k,v]:mp)
cout<<k<<"--"<<v<<"\t";
五、测试代码如下:
#include<iostream>
#include<thread>
#include<atomic>
#include<unordered_map>
#include<map>
using namespace std;
int main(){
map<int,int>mp;
for(int i=0;i<10;i++)mp[i]=i;
cout<<endl<<"iterator:"<<endl;
for(map<int,int>::iterator it=mp.begin();it!=mp.end();++it)
cout<<it->first<<"--"<<it->second<<"\t";
cout<<endl<<"const iterator:"<<endl;
for(map<int,int>::const_iterator it=mp.begin();it!=mp.end();++it)
cout<<it->first<<"--"<<it->second<<"\t";
cout<<endl<<"value_type :"<<endl;
for(map<int,int>::value_type& i:mp)
cout<<i.first<<"--"<<i.second<<"\t";
cout<<endl<<"pair:"<<endl;
for(pair<const int ,int>&i:mp)
cout<<i.first<<"--"<<i.second<<"\t";
cout<<endl<<"auto:"<<endl;
for(auto&[k,v]:mp)
cout<<k<<"--"<<v<<"\t";
getchar();
return 0;
}