首页 > 其他 > 详细

STL之map

时间:2021-03-07 15:25:59      阅读:20      评论:0      收藏:0      [点我收藏+]
//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();
}

技术分享图片

STL之map

原文:https://www.cnblogs.com/weilongZhang/p/14493454.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!