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;
}
前三种方法:若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;
}
相关文章推荐
- 优化Web网站性能
- Recurrent Convolutional Neural Networks for Text Classification阅读笔记
- 安卓自定义属性里的format讲解
- ggplot2画图工作中的代码总结
- 汉诺塔系列
- 关于gdb和shp的FID问题
- [sicily]1194. Message Flood
- 第116讲:Hadoop集群之安装Java、创建Hadoop用户、配置SSH等实战学习笔记
- Python装饰器
- iOS:quartz2D绘图小项目(涂鸦画板)
- 生命的爱
- [大话设计模式]设计模式----单例设计模式
- 数据结构第二次上机实验【链表实现多项式的加法和乘法】
- 《需求工程——软件建模与分析》阅读笔记一
- MySQL学习历程(六):各种查询
- (转)协方差与协方差矩阵
- mac 下sed命令的-i参数
- leetcode Validate Binary Search Tree
- python中的支持向量机实现
- CABasicAnimation的基本使用方法(移动·旋转·放大·缩小)