您的位置:首页 > 其它

std::map 如何插入键值对

2016-03-14 09:48 357 查看
C++ map是经常使用的很方便的一个容器,由键值就可以得到对应的数据。

在使用map时,我们需要将数据保存在map里面,以方便我们的使用。

有两种方式,可以把数据放入map容器:

1.map[键] = 值;直接赋值。

这种方式:当要插入的键存在时,会覆盖键对应的原来的值。如果键不存在,则添加一组键值对。

2.map.insert();这是map自带的插入功能。如果键存在的话,则插入失败,也就是不插入。

使用insert()函数,需要将键值对组成一组才可以插入。

将键值对组成一组有两种方式:一种是make_pair,还有一种是pair。

#include <map>
#include <iostream>

int main()
{
	std::map<int, std::string> mapTest;
	mapTest[1] = "test1";
	mapTest[2] = "test2";	
	mapTest.insert(std::make_pair(3, "test3"));
	mapTest.insert(std::pair<int, std::string>(4, "test4"));
	
	for (auto it = mapTest.begin(); it != mapTest.end();it++)
	{
		std::cout << it->first << " " << it->second.c_str() << std::endl;
	}

	return 0;
}




欢迎指出不妥之处。

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