C++中的map遍历

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;
}

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值