STL map & multimap insert and iterator

map insertion and iterator
map.insert (…); // insert elements into the container, return pair <iterator, bool>

Four ways to insert elements in the
map : suppose map <int, string> mapStu;
method one, insert the object through the pair
mapStu.insert (pair <int, string> (1, "Zhang San"));
method two Insert the object
mapStu.inset (make_pair (2, "Li Si"))by pair;
method three, insert the object
mapStu.insert (map <int, string> :: value_type (3, "Wang Wu" by value_type ));
Way four, insert the value by array
mapStu [4] = "Zhao Liu";
mapStu [5] = "Little Seven";

example:

#include <iostream>
#include <functional>
#include <algorithm>
#include <map>
#include <string>

using namespace std;

int main()
{
	map<int, string> mapStu;

	//方式一 构造一个pair, 然后插入
	pair<map<int, string>::iterator, bool> ret = mapStu.insert(pair<int, string>(1, "张三"));
	if(ret.second == true)
	{
		cout<<"插入成功! value: "<<(*(ret.first)).second<<endl;
	}
	else
	{
		cout<<"插入失败! "<<endl;
	}

	//如果键存在, 则插入会失败
	ret = mapStu.insert(pair<int, string>(1, "小张三"));
	if(ret.second == true)
	{
		cout<<"插入小张三成功! value: "<<(*(ret.first)).second<<endl;
	}
	else
	{
		cout<<"插入小张三失败!"<<endl;
	}

	//方式二 使用make_pair
	mapStu.insert(make_pair(2, "李四"));

	//方式三 使用value_type, 相当于pair<int, string>
	mapStu.insert(map<int, string>::value_type(3, "王五"));

	//方式四 直接使用[]重载, 如果键值对已经存在, 则覆盖原值
	mapStu[4] = "赵六";
	mapStu[4] = "小赵六";

	mapStu[5] = mapStu[6];
	mapStu[7] = mapStu[4];

	for(map<int, string>::iterator it = mapStu.begin(); it != mapStu.end(); it++)
	{
		cout<<"key: "<<(*it).first<<" value: "<<(*it).second<<endl;
	}

	system("pause");
	return 0;
}

Operating environment: vc ++ 2010 learning version
Operating results:
Insert picture description here

note:

1) The first three methods use the insert () method, which returns pair <iterator, bool>

2) The fourth method is very intuitive, but it will be overwritten when it encounters the same key. For example, when inserting the key value of 4, first search the mapStu for the item with the primary key of 4. If it does not exist, insert a pair whose key is 4 and whose value is the default initialization value into mapStu, and then modify the value Become "Zhao Liu". If it is found that the key 4 already exists, modify the value corresponding to this key.

3) string strName = mapStu [8]; // value operation or insert operation

4) Only when mapStu has the key 8 is the correct fetch operation, otherwise it will automatically insert an instance, the key is 8, the value is the initial value when the default construction.

Iterator

map.begin();  //返回容器中第一个数据的迭代器。
map.end();  //返回容器中最后一个数据之后的迭代器。
map.rbegin();  //返回容器中倒数第一个元素的迭代器。
map.rend();   //返回容器中倒数最后一个元素的后面的迭代器。
Published 14 original articles · Like1 · Visits 119

Guess you like

Origin blog.csdn.net/m0_45867846/article/details/105464474