c++中map键值使用方法、查找指定元素
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2021-06-09 22:20:17
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章
初始化和插入值
map<string,int> cmap; //第一种插入值 的方法,没有自动新加,有的话覆盖 cmap["op1"] = 1; cmap["op2"] = 2; string str = "samy"; //第二种直接插入pair cmap.insert(pair(str,3));
map的遍历
//定义一个迭代器,并设置map当前的指针 map<string,int>::iterator ite = cmap.begin(); while(ite!=cmap.end()) { cout<<ite->first<<" "<<ite->second<<endl; ite++; }
反向遍历
map<string,int>::reverse_iterator ite = cmap.rbegin(); while(ite!=cmap.rend()) { cout<<ite->first<<" "<<ite->second<<endl; ite++; }
查找并删除指定的键
map<string,int>::iterator key = cmap.find("Anna"); if(key!=cmap.end()) { cout<<key->second<<endl; //这里是用指定的迭代指针删除 cmap.erase(key); } //也可以直接用指定的键删除 cmap.erase("samy");
清空数据
//用迭代器範圍刪除 : 把整個map清空 cmap.erase(cmap.begin(), cmap.end()); //等同於 cmap.clear()