头文件:#include<map>
map<int,int>a;
就是定义了名字为a的映射函数,a[5]=6其中表示为5映射到6,map的这点与数组十分相似。
字符串的映射也是如此。
但是当你想把一个字符串代表成一个数字或者另一个串时,map是再好不过了。
定义与上面差不多map<string,int>a 这里就是串映射到数字,当你存数据时,像下面这样
a["hello world"]=5;
这样就吧串映射到了数字5了,当你想输出时
cout<<a["hello world"];
他就会输出所映射的值,也就是5
排序
这个map函数是自动排序的,根据map中的key值,也就是前者排序。
如果想改变key的排序可以有如下代码就行了。
struct cmp {
bool operator()(const string a,const string b)const {
return a>b;
}
};
map<string,int,cmp>a;
如果你想根据value排序,这就比较麻烦了 因为map中并不支持直接,需要借助其他的工具
例如 你可以将map放入vector中,再对vector自定义排序即可。
输出
输出时需要特别注意,key时first value是second
for(auto i:a)
cout<<i.first<<" "<<i.second<<endl;
map<string,int>::iterator i;
for(i=a.begin();i!=a.end();i++)
cout<<i->first<<" "<<i->second<<endl;
上面两种都可以输出。
使用地方
需要一个代表另一个,或者打表时也行。
函数
a.erase(x) 删除key值x
时间复杂度近似为
插入: O(logN)
查看:O(logN)
删除:O(logN)