c++中关联容器map的使用

C++关联容器<map>简单总结(转)

补充:

使用count,返回的是被查找元素的个数。如果有,返回1;否则,返回0。注意,map中不存在相同元素,所以返回值只能是1或0。

使用find,返回的是被查找元素的位置,没有则返回map.end()。

#include<string>
#include<iostream>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
 int main(){
      map<string,int> test;
     test.insert(make_pair("test1",1));//test["test1"]=1
     test.insert(make_pair("test2",2));//test["test2"]=2
     map<string,int>::iterator it;
     it=test.find("test0");
     cout<<"test0 find:";
     if(it==test.end()){
         cout<<"test0 not found"<<endl;
     }
     else{
         cout<<it->second<<endl;
     }
     cout<<"test0 count:";
     cout<<test.count("test1")<<endl;
 
     cout<<"test1 find:";
     it=test.find("test1");
     if(it==test.end()){
         cout<<"test1 not found"<<endl;
     }
     else{
         cout<<it->second<<endl;
     }
     cout<<"test1 count:";
     cout<<test.count("test1")<<endl;
 
     cout<<"after inserting test1"<<endl;
     test.insert(make_pair("test1",2));
     cout<<"test1 find:";
     it=test.find("test1");
     if(it==test.end()){
         cout<<"test1 not found"<<endl;
     }
     else{
         cout<<it->second<<endl;
     }
     cout<<"test1 count:";
     cout<<test.count("test1")<<endl;
     return 0;
 }
原文地址:https://www.cnblogs.com/inception6-lxc/p/8360144.html