map的4种常见的插入元素的方式及区别

来源:互联网 发布:java报表导出excel 编辑:程序博客网 时间:2024/06/06 03:08
[cpp] view plain copy
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. #include <string>  
  5. #include <map>  
  6.   
  7. map<int,string> mp;  
  8.   
  9. void showMap()  
  10. {  
  11.     cout<<"\n遍历结果:"<<endl;  
  12.     for(map<int,string>::iterator iter = mp.begin();iter != mp.end(); ++iter)  
  13.     {  
  14.         cout<<iter->first<<" - "<<iter->second<<endl;  
  15.     }  
  16.     cout<<endl;  
  17. }  
  18.   
  19. int main()  
  20. {  
  21.     pair<map<int,string>::iterator,bool> myPair;//保存insert()的返回值  
  22.     //方法[1]  
  23.     myPair = mp.insert(pair<int,string> (1,"student01"));  
  24.     if(true == myPair.second)  
  25.     {  
  26.         cout<<"插入("<<myPair.first->first<<","<<myPair.first->second<<")成功."<<endl;  
  27.     }  
  28.     else  
  29.     {  
  30.         cout<<"插入失败! 对应的key值: "<<myPair.first->first<<endl;  
  31.     }  
  32.       
  33.     //方法[2]  
  34.     myPair = mp.insert(make_pair(2,"student02"));  
  35.     myPair = mp.insert(make_pair(2,"student22"));//插入失败,不会产生覆盖  
  36.   
  37.     if(true == myPair.second)  
  38.     {  
  39.         cout<<"插入("<<myPair.first->first<<","<<myPair.first->second<<")成功."<<endl;  
  40.     }  
  41.     else  
  42.     {  
  43.         cout<<"插入失败! 对应的key值: "<<myPair.first->first<<endl;  
  44.     }  
  45.       
  46.     //方法[3]  
  47.     myPair = mp.insert(map<int,string>::value_type(3,"student03"));  
  48.       
  49.     //方法[4]  
  50.     mp[4] = "student04";  
  51.     mp[4] = "student44";//覆盖  
  52.   
  53.     showMap();  
  54.   
  55.     return 0;  
  56. }  

程序运行结果:



前3种方法,采用的是insert()方法,该方法返回的是pair<iterator,bool>,进行重复插入时,插入失败,不会产生覆盖;
第4种方法,插入重复将会覆盖原有的值。

0 0
原创粉丝点击