以前的数组如int a[],char c[],double d[],其实都是int->其他类型的映射,然而有时下标并不一定是int,这时就要用map来处理了。
1.map定义与访问
注意:1. char[]数组不可以作为键 换用string. key只能是基本类型或容器
2. 可以直接下标访问 eg:m['r']=3 也可以迭代器访问
3. 键值必须唯一
4. 键值自动排序(和set一样,红黑树实现)
#include<iostream>
#include<map>
using namespace std;
int main(){
map<char, int> mp;
mp['r']=10;
mp['a']=20;
mp['m']=30;
mp['m']=40;
cout<<mp['m']<<endl;//40而不是30 第二次覆盖第一次的
map<char, int>::iterator it;
for(it=mp.begin();it!=mp.end();it++){
printf("%c %d\n", it->first,it->second);//会自动排好序
}
return 0;
}
注:各种类型key不存在(无此对映射关系)时的默认输出
key不存在(无此对映射关系)时:
int返回0
string返回""空字符串
char返回ascii为0的字符
#include<iostream>
#include<map>
using namespace std;
int main(){
map<char, int> mp;
mp['a']=10;
cout<<mp['b']<<endl;//key不存在(无此对映射关系) int返回0
map<int, string> mp1;
mp1[1]="one";
cout<<(mp1[2]=="")<<endl;//key不存在(无此对映射关系) string返回""空字符串
map<int, char> mp2;
mp2[1]='a';
cout<<mp2[2]<<endl;//key不存在(无此对映射关系) char返回ascii为0的字符
cout<<char(0);
return 0;
}
2.find()
mp.find(key)返回key对应的指针it 失败返回mp.end() 一样的套路 最后指针+1
#include<iostream>
#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\n", it->first,it->second);
return 0;
}
3.erase()
erase(iterator) 删除iterator指向的那对
erase(key) 删除key为key的那对映射
erase(first,last) 删除迭代器[first,last)内的元素
#include<iostream>
#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');
mp.erase(it);
for(it=mp.begin();it!=mp.end();it++){
printf("%c %d\n", it->first,it->second);//会自动排好序
}
return 0;
}
#include<iostream>
#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');
mp.erase('b');
for(it=mp.begin();it!=mp.end();it++){
printf("%c %d\n", it->first,it->second);//会自动排好序
}
return 0;
}
#include<iostream>
#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');
mp.erase(it,mp.end());
for(it=mp.begin();it!=mp.end();it++){
printf("%c %d\n", it->first,it->second);//会自动排好序
}
return 0;
}
4.size() clear()
#include<iostream>
#include<map>
using namespace std;
int main(){
map<char,int> mp;
mp['a']=1;
mp['b']=2;
mp['c']=3;
cout<<mp.size()<<endl;
mp.clear();
cout<<mp.size()<<endl;
return 0;
}
5.map常见用途
1.需要建立字符(或字符串)与整数之间映射的题目,使用map可以减少代码量
2.判断大整数或者其他类型数据是否存在的问题,可以把map当做bool数组来用
3.字符串和字符串的映射
map键唯一,若一个键要对应多个值,则只能用multimap
unorder_map 不按key排序的map,速度远远快于map