map的insert方法

C++语言 码拜 9年前 (2015-11-08) 1796次浏览
#include <iostream>
#include<map>
#include<string>
using namespace std;
int main()
{
	map<int, string> mapMy;
	mapMy[0] = "My";
	mapMy[2] = "1";
	map<int, string> mapYou;
	mapYou[0] = "a";
	mapYou[1] = "b";
	mapYou[2] = "c";
	mapMy.insert(mapYou.begin(), mapYou.end());
	for (auto iter2 = mapMy.begin(); iter2 != mapMy.end(); ++iter2)
	{
		cout << iter2->second << endl;
	}
	/*
	输出是
	My
	b
	1

	*/
	return 0;
}

这是为什么呢?

解决方案:100分
map中不允许有键值相同的两个元素,你的mapYou中的0和2为键的已经有了,所以实际只插入了mapYou[1] = “b”;只一项
假如想允许有重复键值的元素,把map改成multimap即可(不过multimap是不支持mapMy[0] = “My”; 这种方式插入元素的)

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明map的insert方法
喜欢 (1)
[1034331897@qq.com]
分享 (0)