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

#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;//保存insert()的返回值
	//方法[1]
	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;
	}
	
	//方法[2]
	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;
	}
	
	//方法[3]
	myPair = mp.insert(map<int,string>::value_type(3,"student03"));
	
	//方法[4]
	mp[4] = "student04";
	mp[4] = "student44";//覆盖

	showMap();

	return 0;
}

程序运行结果:



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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值