map

头文件

首先要引入头文件  #include <map> . 并使用命名空间  using namespace std;

1、插入元素

用pair 或者 make_pair 均可,map键值不能重复。

map1.insert(pair<int,string>(123,"aaaaa")); //pair
map1.insert(make_pair<int,string>(456,"bbbbb")); //make_pair

2、访问map中元素

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

3、从map对象中删除元素

	it = map1.begin();
	it++;
	map1.erase(it);  //删除迭代器it指向的元素,it必须指向map1中存在的元素,而且不能等于map1.end()
	map1.erase(123); //删除map1中键值为123的元素

4、判断map是否为空

	cout << "empty:"<< map1.empty() <<endl;
	map1.erase(123); //删除map1中键值为123的元素
	map1.erase(456);
	cout << "empty:"<< map1.empty() <<endl;

5、统计map中元素个数

	cout << "size:"<< map1.size() <<endl;
	map1.erase(123); //删除map1中键值为123的元素
	cout << "size:"<< map1.size() <<endl;
	map1.erase(456);
	cout << "size:"<< map1.size() <<endl;

6、排序

map默认是按照键值从小到大排序的

原文地址:https://www.cnblogs.com/cgc0415/p/8796929.html