STL之map

//STL之MAP用法
//以往定义的数组实现了int类型向其他类型的映射
//现在想要实现其他类型向其他类型的映射
//通过map实现键值对存储
#include<stdio.h>
#include<map>
using namespace std;
int main() {
	//定义
	map<char,int> mp;
	mp['s'] = 45;
	mp['z'] = 25;
	mp['a'] = 12;
	//元素访问方式
		//方式一 通过键直接得到
	printf("下标寻找s %d\n",mp['s']);
		//方式二 通过迭代器
	map<char,int>::iterator it = mp.begin();
	printf("迭代器寻找第一个 元素%c %d\n",it->first,it->second);
		//遍历输出后会发现,此时的顺序已经发生变化,map会以键从小到大顺序自动排序,用红黑树实现。 
	for(it; it!=mp.end(); it++) {
		printf("%c %d\n",it->first,it->second);
	}
	//find函数,返回迭代器
	it = mp.find('a');
	
	printf("寻找a的迭代器%c %d\n",it->first,it->second);
	//erase函数
		//通过键直接删除
	mp.erase('z');//删除z  
		//通过迭代器删除 
	mp.erase(mp.find('a'));//删除'a' 
	printf("删除之后\n"); 
	for(it = mp.begin(); it!=mp.end(); it++) {//遍历查看当前map中元素值 
		printf("%c %d\n",it->first,it->second);
	}
	//erase可以删除迭代器区间 ,左闭右开。 
	//size函数
	printf("长度%d",mp.size()); 
	//clear函数 
	mp.clear();
}

posted @ 2021-03-07 08:42  我就是隔壁老张  阅读(50)  评论(0编辑  收藏  举报