1.map
如何定义一个map
map<typename1,typename2> mp;
如果是字符串到整型的映射,必须使用string而不是char数组.
2.map容器内元素的访问
(1).通过下标访问
map中的键是唯一的.
例:
#include<stdio.h>
#include<map>
using namespace std;
int main(){
mao<char,int>mp;
mp['c'] = 20;
mp['c'] = 30; //20被覆盖
printf("%d\n",mp['c']); //输出30
return 0;
}
(2)通过迭代器访问
map迭代器
map<typename1,typename2>::terator it;
可以使用it->first访问键,it->second访问值,或(*it).first,(*it).second.
map会以键从小到大的顺序自动排序,map内部是使用红黑树实现的(set也是).
让map自定义排序
#include<bits/stdc++.h>
using namespace std;
struct CmpByKeyLength {
bool operator()(const string& k1, const string& k2)const {
return k1.length() > k2.length(); //按键的长度从大到小排序k1排在k2的前面
}
};
int main(){
map<string, int, CmpByKeyLength> name_score_map;
name_score_map["LiMin"] = 90;
name_score_map["ZiLinMi"] = 79;
name_score_map["BoB"] = 92;
map<string, int>::iterator iter;
for ( iter = name_score_map.begin();iter != name_score_map.end();++iter) {
cout << (*iter).first << endl;
}
return 0;
}
输出
比较两个字符串的字典序大小strcmp函数
#include <iostream>
#include <cstring>
using namespace std;
int main(){
char* str1="hello";
char* str2="hell";
char *str3="helloo";
char *str4="hello";
//原型extern int strcmp(const char *s1,const char *s2);
cout<<strcmp(str1,str2)<<endl;//返回1;
cout<<strcmp(str1,str3)<<endl;//返回-1;
cout<<strcmp(str1,str4)<<endl;//返回0.
}
3.map常用函数解析
(1)find()
find(key)返回键为key的映射的迭代器.
示例:
#include<stdio.h>
#include<map>
using namespace std;
int main(){
mao<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); //输出结果:b 2
return 0;
}
(2)erase()
erase()的用法:
1.删除单个元素.
2.删除一个区间的所有元素.
1.删除单个元素
第一种方式:mp.erase(it),it为需要删除的元素的迭代器,需要find()函数配合.
输出:
a 1
c 3
第二种方式:mp.erase(key),key为欲删除的映射的键.
2.删除一个区间内的所有元素
mp.erase(first,last),其中first为需要删除的区间的起始迭代器,而last则为需要删除的区间的末尾迭代器的下一个地址,也即为删除左闭右开的区间[first,last).
#include<stdio.h>
#include<map>
using namespace std;
int main(){
mao<char,int>mp;
mp['a'] = 1;
mp['b'] = 2;
mp['c'] = 3;
map<char,int>::iterator it = mp.find('b');
//mp.end()是mp最后一个元素的后一个迭代器
mp.erase(it,mp.end()); //删除it之后的所有映射,即b 2和c 3
for(map<char,int>::iterator it = mp.begin();it!=mp.end();++it){
printf("%c %d\n",it->first,it-second);
}
return 0;
}
输出:
a 1
(3)size()
mp.size()用来获得map中映射的个数.
STL中大多数容器都可用size()获取长度
(4)clear()
mp.clear()用来清空map中所有的元素.
对STL进行遍历的通用方法:
int main(int argc, char* argv[])
{
map<string, string> mapData;
mapData["a"] = "aaa";
mapData["b"] = "bbb";
mapData["c"] = "ccc";
for (map<string, string>::iterator i=mapData.begin(); i!=mapData.end(); i++)
{
if (i->first == "b")
{
mapData.erase(i);
}
}
return 0;
}
对于string,vector等,可以用数字下标,从0到size()-1.
4.map的常见用途
(1)需要建立字符(或字符串)与整数之间的映射的题目
(2)判断大整数或其他类型数据是否存在的题目,可以把map当bool数组使用.因为map有find()函数.
(3)字符串与字符串的映射也有可能遇到.
如果一个键需要对应多个值,就只能用multimap,一般用的少.
C++11中新增了unordered_map,以散列(Hash)代替map内部的红黑树实现,速度比map要快很多,用这个比较多.