1、map顺序遍历
使用iterator迭代器进行遍历。
2、map逆序遍历
使用reverse_iterator逆向迭代器进行遍历。
3、判断map中是否含有某键值
通过 map::find(key) 来进行查找判断
#include <bits/stdc++.h>
using namespace std;
map<string,int> mp;
string key = "test";
string f[3] = {"abd","abc","abb"};
void testFind(){
if(mp.find(key)==mp.end()){
cout<<"该map中不含有键为key的键值对\n";
}
if(mp.find(f[0])!=mp.end()){
map<string,int>::iterator it = mp.find(f[0]);
cout<<"该map中含有key为:"<<f[0]<<" 的键值对\n";
cout<<it->first<<" "<<it->second<<endl;
}
}
void testOrder(){//顺序遍历
cout<<"顺序遍历"<<endl;
for(auto it = mp.begin();it!=mp.end();it++){
cout<<it->first<<" "<<it->second<<endl;//first代表键,second代表值
}
}
void testROrder(){
cout<<"逆序遍历"<<endl;
//2、采用逆序迭代器iterator的方式进行迭代
map<string,int>::reverse_iterator it;//逆向迭代器
for(it = mp.rbegin();it!=mp.rend();it++){//逆向迭代加即为减
cout<<it->first<<" "<<it->second<<endl;
}
}
int main()
{
mp[f[0]]++;
mp[f[1]]++;
mp[f[2]]++;
testFind();
testOrder();
testROrder();
return 0;
}