一:介绍:
map是STL的一个关联容器,有key 和value两个值,其类型可以自己定义,每个关键字在map中只能出现一次,key不能修改,value可以修改;map同set、multiset、multimap(与map的差别仅在于multimap允许一个键对应多个值)内部数据结构都是红黑树,查找时间复杂度为O(logn)。
如此低时间复杂度的容器在竞赛中的使用频率自然不低。
二:头文件:
#include<map>
三:定义:
map<类型名,类型名> 变量名
//例如
map<int,string> s;
map<string,int> s;
四:含义:
大家应该都注意到了吧,map中有两个类型名。
第一个类型名:key值,也就是索引值,它就像数组中的[]内的数字,key只在关键字中出现一次。
第二个类型名:value值,他就是key对应的数值。
五:插入元素:
#include<iostream>
#include<map>
using namespace std;
int main()
{
map<int,string> s;
s.insert(pair<int,string>(1,"wwyz"));
s.insert(pair<int,string>(4,"booyi"));
s.insert(pair<int,string>(2,"computer"));
}
这样就实现了插入.
map中的插入方式有很多,这里介绍比较常见的两种.
第一种:如同上面所示,因为c++中map是一中pair类型的元素,所保存的值都存在二叉树中,所以插入时可以用pair来插入
变量名.insert(pair<类型名,类型名>(数据,数据))
第二种:在c++中,对于map的[]进行了重载,我们可以用[]来对map赋值。
// 变量名[key]=value;
//例如
#include<iostream>
#include<map>
using namespace std;
int main()
{
map<int,string> s;
s[1]="wwyz";
s[2]="booyi";
s[3]="computer";
}
六:获取元素:
一:与插入一样,我们可以用重载函数的[]来对map索引;
#include<iostream>
#include<map>
using namespace std;
int main()
{
map<int,string> s;
s[1]="wwyz";
s[2]="booyi";
s[3]="computer";
for(int i=1;i<=3;i++)
cout<<s[i]<<endl;
}
即可打印出:
wwyz
booyi
computer
二:可以使用map迭代器
map<类型名,类型名> :: iterator it
#include<iostream>
#include<map>
using namespace std;
int main()
{
map<int,string> s;
s[1]="wwyz";
s[2]="booyi";
s[3]="computer";
for(map<int,string> ::iterator it=s.begin();it!=s.end();it++)
cout<<it->first<<' '<<it->second<<endl;
}
输出:
1 wwyz
2 booyi
3 computer
七:特性:
map是一种会自动按照key排序的容器.
#include<iostream>
#include<map>
using namespace std;
int main()
{
map<int,string> s;
s[3]="wwyz";
s[2]="booyi";
s[1]="computer";
for(map<int,string> ::iterator it=s.begin();it!=s.end();it++)
cout<<first<<' '<<second<<endl;
}
比如我们修改插入map的顺序,输出值不变.
若把string当做key,则按照ascii排序.
八:查找元素:
查找一个元素,即判定此元素是否在map中出现过.
一:find()函数
它返回一个迭代器,当数据出现时,返回的是数据所在位置的迭代器;若map中没有要查找的数据,返回的迭代器等于end函数返回的迭代器。
#include<iostream>
#include<map>
using namespace std;
int main()
{
map<int,string> s;
s[3]="wwyz";
s[2]="booyi";
s[1]="computer";
map<int,string> ::iterator it;
it=s.find(2);
cout<<it->second<<endl;
}
二:count(),此函数缺点就是不能知道他的具体位置,只知道到底有没有,有返回1,无返回0;
代码就不再展示了。
九:删除:
erase()函数可以删除其索引值对应的map;
s.erase(1);//删除key为1的值
s.erase(s.begin(),s.end());//删除所有值
十:排序:
sort()只支持对vector,queue等容器排序,对map按照value排序可以将其转化为vector来排序.
#include <iostream>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;
bool cmp(pair<string,int> a, pair<string,int> b) {
return a.second < b.second;
}
int main()
{
map<string, int> ma;
ma["wwyz"] = 1;
ma["booyi"] = 9;
ma["computer"] = 3;
ma["good"] = 2;
vector< pair<string,int> > vec(ma.begin(),ma.end());
sort(vec.begin(),vec.end(),cmp);
for (vector< pair<string,int> >::iterator it = vec.begin(); it != vec.end(); ++it)
{
cout << it->first << " " << it->second << endl;
}
return 0;
}