C++的map和multimap本质都是排序的平衡二叉树。其中不同的点在于
另外需要提及的一点是它们的删除操作,在删除某个迭代器的时候会导致迭代器失效。下面的代码主要介绍几个特殊的查找函数:
代码演示:
#include
#include
#include
using namespace std;
bool cmp(const pair<int,int> &elem){
return elem.second==3;
}
int main() {
//赋值
map<int,int> coll={{1,7},{2,4},{3,2},{4,3},{5,6},{6,1},{7,3}};
//查找键值为3的元素
auto posKey=coll.find(3);
if(posKey!=coll.end()){
cout<<"key-3:("<<posKey->first<<","<<posKey->second<<")"<<endl;
}
cout<<"======================"<<endl;
//查找值为3的元素
auto posVal=find_if(coll.begin(),coll.end(),cmp);
if(posVal!=coll.end()){
cout<<"value-3:("<<posVal->first<<","<<posVal->second<<")"<<endl;
}
cout<<"======================"<<endl;
//给multimap赋值
multimap<int,string> multicoll={{1,"h"},{1,"i"},{1,"j"},{3,"world"},{4,"six"},{4,"seven"},{6,"what"},{6,"yy"},{7,"what"},{8,"niu"}};
//测试查找key为1的上下元素
pair<multimap<int,string>::iterator,multimap<int,string>::iterator> ret=multicoll.equal_range(1);
for(auto pos=ret.first;pos!=ret.second;++pos){
cout<<"key-1:("<<pos->first<<","<<pos->second<<")"<<endl;
}
cout<<"======================"<<endl;
//找出<=4的元素进行删除
auto pos1=multicoll.lower_bound(4);
auto pos2=multicoll.begin();
while(pos2!=pos1){
if(pos2->first<=4) {
pos2 = multicoll.erase(pos2);//先缓存再删除
continue;//这一步很重要,删除完之后不要pos2++
}
pos2++;
}
for(auto pos3=multicoll.begin();pos3!=multicoll.end();++pos3){
cout<<"key:("<<pos3->first<<","<<pos3->second<<")"<<endl;
}
cout<<"======================"<<endl;
//删除>=6的元素
auto pos4=multicoll.upper_bound(4);
while(pos4!=multicoll.end()){
if(pos4->first>=4) {
pos4 = multicoll.erase(pos4);//先缓存再删除
continue;//这一步很重要,删除完之后不要pos2++
}
pos4++;
}
// 查看删除后的mutlicoll
for(auto pos3=multicoll.begin();pos3!=multicoll.end();++pos3){
cout<<"key:("<<pos3->first<<","<<pos3->second<<")"<<endl;
}
return 0;
}
运行结果
key-3:(3,2)
======================
value-3:(4,3)
======================
key-1:(1,h)
key-1:(1,i)
key-1:(1,j)
======================
key:(4,six)
key:(4,seven)
key:(6,what)
key:(6,yy)
key:(7,what)
key:(8,niu)
======================
key:(4,six)
key:(4,seven)
进程已结束,退出代码 0