- #include <iostream>
- using namespace std;
-
- #include <string>
- #include <map>
-
- map<int,string> mp;
-
- void showMap()
- {
- cout<<"\n遍历结果:"<<endl;
- for(map<int,string>::iterator iter = mp.begin();iter != mp.end(); ++iter)
- {
- cout<<iter->first<<" - "<<iter->second<<endl;
- }
- cout<<endl;
- }
-
- int main()
- {
- pair<map<int,string>::iterator,bool> myPair;
-
- myPair = mp.insert(pair<int,string> (1,"student01"));
- if(true == myPair.second)
- {
- cout<<"插入("<<myPair.first->first<<","<<myPair.first->second<<")成功."<<endl;
- }
- else
- {
- cout<<"插入失败! 对应的key值: "<<myPair.first->first<<endl;
- }
-
-
- myPair = mp.insert(make_pair(2,"student02"));
- myPair = mp.insert(make_pair(2,"student22"));
-
- if(true == myPair.second)
- {
- cout<<"插入("<<myPair.first->first<<","<<myPair.first->second<<")成功."<<endl;
- }
- else
- {
- cout<<"插入失败! 对应的key值: "<<myPair.first->first<<endl;
- }
-
-
- myPair = mp.insert(map<int,string>::value_type(3,"student03"));
-
-
- mp[4] = "student04";
- mp[4] = "student44";
-
- showMap();
-
- return 0;
- }
程序运行结果:
![](https://img-blog.csdn.net/20150817080135896)
前3种方法,采用的是insert()方法,该方法返回的是pair<iterator,bool>,进行重复插入时,插入失败,不会产生覆盖;
第4种方法,插入重复将会覆盖原有的值。