Brief introduction of STL map / multimap

Introduction to map / multimap
map is a standard associative container. The elements stored in a map are a sequence of key-value pairs, called (key, value) key-value pairs. It provides the ability to quickly retrieve data based on keys. (It's like holding a courier number and going to get a courier)
Insert picture description here
Example:

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

using namespace std;

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

	mapStu.insert(pair<int, string>(1, "张三"));
	mapStu.insert(pair<int, string>(2, "李四"));
	mapStu.insert(pair<int, string>(3, "王五"));

	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

1) The key value in the map is unique. The elements in the collection are arranged in a certain order. The element insertion process is inserted according to the sorting rules, so the insertion position cannot be specified.
2) The specific implementation of the bottom layer of the map is a data structure of a balanced binary tree using a red-black tree variant. Insert operation, delete and retrieval operations are much faster than vector.
3) Map can directly access the value corresponding to the key, and supports the [] operator, such as map [key] = value.

The difference between multimap and map:
map supports unique key values, each key can only appear once; and the same key in multimap can appear multiple times. Multimap does not support the [] operator.

example:

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

using namespace std;

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

	mapStu.insert(pair<int, string>(1, "张三"));
	mapStu.insert(pair<int, string>(2, "李四"));
	mapStu.insert(pair<int, string>(3, "王五"));

	//multimap 不支持[]操作, map支持
	//mapStu[4] = "赵六";

	//multimap 支持相同的key 插入
	mapStu.insert(pair<int, string>(3, "小王五"));

	for(multimap<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

Published 14 original articles · Like1 · Visits 119

Guess you like

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