map函数
map函数极为映射
(map的键和值是唯一的)
例:int a[100];即为a[i]=k;将i映射到k,int型映射到int,数组的弊端就是只能映射到int型map可以避免这种弊端.
1.map定义方法map<type1,type2>mp;
mp为变量名,就相当于上面数组的名字a。(
如果是字符串到整型的映射,必须使用string而不能用char)
2.map的访问方式:
第一:像以前的那种访问方式用代码说明。
#include<stdio.h>
#include<map>
using namespace std;
int main()
{
map<char,int>mp;
mp['c']=20;
mp['c']=30;
printf("%d\n",mp['c']);
}
第二:通过迭代器访问
(map迭代器的定义和其他STL容器定义的方式相同)
map<type,type>::iterator it;//使用一个it来同时访问键和值。也可以用it->first访问键,用it->second访问值。
map会以键从小到大的的顺序自动排序
#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);
}
return 0;
}
这段代码表示了连续访问的方法,访问键和值。
3.与map有关的各种处理函数。
find()找到map中的某一个键,并输出。
erase()删除单个元素,删除一个区间内的所有元素,
//删除单个元素,可以直接删除这个键。例:mp.erase('b');
//删除单个元素的迭代器。例:map<char,int>::iterator it=mp.find('b'); mp.erase(it);
//删除一个区间内的元素。例:map<char,int>::iterator it=mp.find('b'); mp.erase(it,mp.end());
size() map中映射对数
clear()清空map中所有元素