您的位置:首页 > 其它

map容器(4种元素添加方法的异同)

2015-10-13 21:40 435 查看
4种元素添加方法的异同

前三种方法:若key已经存在,则会报错;第四种方法:若key已经存在,则修改。

示例如下:

#include <iostream>

using namespace std;

#include <map>

#include <string>

int main()

{

//typedef pair<iterator, bool> _Pairib;

map<int,string> map1;

//方法1

pair<map<int,string>::iterator,bool> mypair1=map1.insert(pair<int,string>(1,"teacher01"));

map1.insert(pair<int,string>(2,"teacher02"));

//方法2

pair<map<int,string>::iterator,bool> mypair2=map1.insert(make_pair(3,"teacher03"));

map1.insert(make_pair(4,"teacher04"));

//方法3

pair<map<int,string>::iterator,bool> mypair3=map1.insert(map<int,string>::value_type(5,"teacher05"));

if(mypair3.second!=true)

{

cout<<"key5插入失败"<<endl;

}

else

{

cout<<"key5插入成功"<<mypair3.first->first<<"\t"<<mypair3.first->second<<endl;

}

pair<map<int,string>::iterator,bool> mypair4=map1.insert(map<int,string>::value_type(5,"teacher55"));

if(mypair4.second!=true)

{

cout<<"key5.2插入失败"<<endl;

}

else

{

cout<<"key5.2插入成功"<<mypair4.first->first<<"\t"<<mypair4.first->second<<endl;

}

//方法4

map1[7]="teacher07";

map1[7]="teacher77";

//map遍历

for(map<int,string>::iterator it=map1.begin();it!=map1.end();it++)

{

cout<<it->first<<"\t"<<it->second<<endl;

}

cout<<"-----------遍历结束----------"<<endl;

system("pause");

return 0;

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: