map的常用用法详解

//头文件
#include<map>
using namespace std;//c++
//用法
//map可以将任何数据类型(包括STL(Standard Template Library))
//映射到任何基本类型(包括STL容器)
map<typename1,typename2>mp;//第一个是键的类型,第二个是值的类型
//注意
如果是字符串到整型的映射,必须使用string而不能用char数组
因为不能用数组作键。
//访问方式1)直接通过下标访问和正常数组访问一样
(2)迭代器访问
map<typename1,typename2>::iterator it;
#include<stdio.h>
#include<map>
using namespace std;
int main(){
	map<char,int>mp;
	mp['m']=20;
	mp['r']=30;
	mp['a']=40;
	for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++)
	{
	  printf("%c %d\n",it->first,it->second);
	}//it->first访问键,it->second访问值 
	return 0;
	}//map会将键按照从小到大自动排序

注意:map内部会将键从小到大自动排序
find()
find(key),配合迭代器使用查找某一个键的位置

#include<stdio.h>
#include<map>
using namespace std;
int main()
{
	map<char,int>mp;
	mp['a']=1;
	mp['b']=2;
	mp['c']=3;
	map<char,int>::iterator it=mp.find('b');
	printf("%c %d",it->first,it->second);
	return 0;
	}

erase()
erase()有两种用法:
1,删除单个元素
2,删除一个区间的所有元素
删除一个区间的代码
mp.erase(first,last)
last为需要删除的区间的末尾迭代器的下一个地址,[first,last)
注意
mp.begin()是指第一个元素的下标地址
mp.end()是指最后一个元素下标的后一个地址

#include<stdio.h>
#include<map>
using namespace std;
int main(){
	map<char,int>mp;
	mp['a']=10;
	mp['b']=20;
	mp['c']=30;	
	map<char,int>::iterator it=mp.find('b');
	mp.erase(it,mp.end());
	for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++)
	printf("%c %d\n",it->first,it->second);
	return 0;
}

size()
用来获取map中的对数

clear()
用来清空map中所有元素

个人见解
以前一直开一个大数组来用
遇到通过char查询int的时候就a[(int)c]来进行操作,但有时候数组太大浪费空间,而且数组是不能开无限大的,局限很大所以学会map救我一命

后续

使用经验
举例说明;
在解题过程中
map<int,int>mp;
//只要出现mp[int]声明就相当于在mp加入了元素,因为map会自动初始化为对应的值。
//所以mp.size()会变化。
if(mp[b]!=0)//mp中多了键为b的元素。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章