map:映射
定义int型数组时,实际是定义了一个从int型到int型的映射,array[0]=25,就是将0映射到25;
double型数组则是将int型映射到double型,如db[0]=3.14,db[1]=0.01。
map可以将任何基本类型(包括STL容器)映射到任何基本类型(包括STL容器),如string到int的映射。
map头文件:#include < map> using namespace std;
map定义
map<typename1,typename2> mp; //键,值
map<int,int> mp; //相当于普通的int型数组
map<string,int> mp; //字符串到整型的映射,不能用char,因为char本身就是数组,不能作为键值
map<set<int>,string> mp; //将set容器映射到一个字符串
map容器内元素的访问
通过下标访问
#include <stdio.h>
#include <map>
using namespace std;
int main(){
map<char,int> mp;
mp['c']=20;
mp['c']=30;
//map中的键是唯一的,因此只会输出30
printf("%d\n",mp['c']);
return 0;
}
通过迭代器访问
map迭代器的定义:
map<typename1,typename2>::iterator it;
map必须能通过一个it来同时访问键和值。可以用it->first访问键,it->second访问值
#include <stdio.h>
#include <map>
using namespace std;
int main(){
map<char,int> mp;
mp['m']=20;
mp['c']=30;
mp['a']=40;
for(map<char,int>::iterator it = mp.begin();it!=mp.end();it++){
//输出 键(char) 值 (int)
printf("%c %d\n",it -> first, it -> second);
}
return 0;
}
map会以键从小到大的顺序自动排序,即a<c<m的顺序排列这三对映射。因为map内部是红黑树实现的(set也是),在建立映射的过程中会自动实现从小到大的排序功能。
map常用函数实例
find( )
find(key)返回键为key的映射的迭代器
#include <stdio.h>
#include <map>
using namespace std;
int main(){
map<char,int> mp;
mp['m']=2;
mp['c']=3;
mp['a']=4;
map<char,int>::iterator it=mp.find('c');
printf("%c %d\n",it->first,it->second);
return 0;
}
erase( )
1.删除单个元素
- mp.erase(it)
#include <stdio.h>
#include <map>
using namespace std;
int main(){
map<char,int> mp;
mp['m']=2;
mp['c']=3;
mp['a']=4;
map<char,int>::iterator it=mp.find('c');
mp.erase(it);
for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++){
printf("%c %d\n",it->first,it->second);
}
return 0;
}
- mp.erase(key)
#include <stdio.h>
#include <map>
using namespace std;
int main(){
map<char,int> mp;
mp['m']=2;
mp['c']=3;
mp['a']=4;
//map<char,int>::iterator it=mp.find('c');
mp.erase('c'); //删除键为c的映射
for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++){
printf("%c %d\n",it->first,it->second);
}
return 0;
}
2.删除区间内所有元素
mp.erase(first,last),first为需要删除的区间的起始迭代器,last为需要删除的区间的末尾迭代器的下一个地址
#include <stdio.h>
#include <map>
using namespace std;
int main(){
map<char,int> mp;
mp['m']=2;
mp['c']=3;
mp['a']=4;
map<char,int>::iterator it=mp.find('c');
mp.erase(it,mp.end()); //删除c,m
for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++){
printf("%c %d\n",it->first,it->second);
}
return 0;
}
size( )
获得map中映射的对数
#include <stdio.h>
#include <map>
using namespace std;
int main(){
map<char,int> mp;
mp['m']=2;
mp['c']=3;
mp['a']=4;
printf("%d\n",mp.size());
return 0;
}
clear( )
清空map中所有元素
#include <stdio.h>
#include <map>
using namespace std;
int main(){
map<char,int> mp;
mp['m']=2;
mp['c']=3;
mp['a']=4;
mp.clear();
printf("%d\n",mp.size());
return 0;
}
map常见用途
1.字符与整数映射
2.判断大整数或其他类型数据是否存在,可以把map当bool数组用
3.字符串和字符串的映射
延申:如果一个键需要对应多个值,只能用multimap