C++ STL中map的四种插入形式

#include <iostream>
using namespace std;

#include "map"
#include "string"

void testInsert(map<int, string> &m)
{
	//first insert method
	m.insert(pair<int, string>(1, "teacher1"));
	//second insert method
	m.insert(make_pair<int, string>(2, "teacher2"));
	//third insert method
	m.insert(map<int, string>::value_type(3, "teacher3"));
	//forth insert method
	m[4] = "teacher4";
	//四种方法异同:前三种方法当出现重复键时,编译器会报错,而第四种方法,当键重复时,会覆盖掉之前的键值对。

	//使用前三种方法可以的到一个返回值pair,该pair的类型是 pair<map<int, string>::iterator, bool>
	pair<map<int, string>::iterator, bool> pair1 = m.insert(pair<int, string>(1, "teacher5"));
	if (pair1.second)
	{
		cout << "插入成功" << endl;
	}
	else
	{
		cout << "插入失败" << endl;
	}
	m[4] = "teacher6";
	for (map<int, string>::iterator it = m.begin(); it != m.end(); it++)
	{
		cout << it->first << "\t" << it->second << endl;
	}
}

int main()
{
	map<int, string> m;
	testInsert(m);
	return 0;
}

  区别:详见代码注释。

转载于:https://www.cnblogs.com/qkqBeer/articles/10838880.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值