map的用法

点击查看代码
#include<cstdio>
#include<map>
#pragma warning(disable:4996)
using namespace std;

int main() {
	map<char, int> mp; //键char->值int
	
	//使用下标访问map容器
	mp['c'] = 20; //创建一个键c,映射值为20
	mp['c'] = 30; //键c映射值改为30,键具有唯一性
	printf("%d\n", mp['c']); //输出键c映射的值

	//使用迭代器访问map容器
	mp['m'] = 20; //map容器中的键值自动按照字典序升序排序
	mp['r'] = 30;
	mp['a'] = 40;
	map<char, int>::iterator it; //创建迭代器it
	//map容器first和second成员分别是键值和映射的值
	for (it=mp.begin(); it != mp.end(); it++) {
		printf("%c %d\n", it->first, it->second); //mp:a 40,m 20,r 30
	}

	mp['a'] = 1;
	mp['b'] = 2;
	mp['c'] = 3;
	//find(key)返回指向键值为key的迭代器
	map<char, int>::iterator it = mp.find('b'); //it指向mp['b']
	printf("%c %d\n", it->first, it->second); //输出it指向的键值和映射的值,即b 2

	mp.erase(it); //erase(it)删除迭代器it指向的键(同时删除映射的值)
	mp.erase('b'); //erase(key)删除键值为key的键(同时删除映射的值)
	for (it = mp.begin(); it != mp.end(); it++) {
		printf("%c %d\n", it->first, it->second); //mp:a 1, c 3
	}

	mp['a'] = 1;
	mp['b'] = 2;
	mp['c'] = 3;	
	//erase(first, last)删除[first, last)区间内的所有键(同时删除映射的值
	it = mp.find('b'); //指向mp[1]的键'b'
	mp.erase(it, mp.end()); //删除mp[1,3)区间内的所有键(同时删除映射的值)
	for (it = mp.begin(); it != mp.end(); it++) {
		printf("%c %d\n", it->first, it->second); //mp:a 1
	}

	mp['a'] = 1;
	mp['b'] = 2;
	mp['c'] = 3;
	printf("%d\n", mp.size()); //size()返回map容器中映射的对数
	mp.clear(); //清空map容器中所有的数据

	return 0;
}
posted @ 2022-09-30 23:02  zhaoo_o  阅读(9)  评论(0编辑  收藏  举报