map是一种关联式容器,它可以提供一对一的映射关系,即key_value的对应。map是一棵红黑树,它具有自动排序的功能,默认是升序(或者字典序从小到大)。map的特点是删除或者增加一个结点对迭代器影响很小,并且我们只能修改value的值,而不能企图更改key的值
//使用map需要头文件
#include<map>
1.声明和初始化
map<type,type>name; //type是所需要的数据类型,name是自己取得名字
eg:map<string,int>mp;
2.插入操作
//在此之前,先介绍一下pair
//(1)pair的作用是将两个数据整合为一组数据
//初始化
pair<type,type>name;
eg:pair<string,int>stu;
pair<string,int>stu1("bob",19); //pair可以通过这种方式进行初始化
//pair具有两个两个共有函数first和second的访问
stu.first="hah";stu.second=28; //赋值
//访问时直接通过成员访问运算符就可以
//pair重载了运算符,可以用<判断pair的字典序大小,==判断二者是否相等
//map的插入,使用insert函数或者数组
map<string,int>mp;
//1.通过使用pair进行插入
mp.insert(pair<string,int>("bob",19));
//2.通过value_type插入
mp.insert(map<string,int>::value_type ("bob",19));
//因为map中的key是唯一的,所以重复的key这两种方式不会再插入
//3.数组
mp["bob"]=19; //这种方式会继续插入重复的key,并且把之前的value覆盖掉,保存的是最后的value;
3.遍历
(1)使用迭代器
map<string,int>stu;
stu.insert(pair<string,int>("bob",98));
stu.insert(map<string,int>::value_type ("laiu",89));
stu.insert(map<string,int>::value_type ("sakj",90));
stu["heelo"]=87;
map<string,int>::iterator iter; //正向
for(iter=stu.begin();iter!=stu.end();iter++)
cout<<iter->first<<' '<<iter->second<<endl;
//反向
map<string,int>::reverse_iterator it;
for(iter=stu.rbegin();iter!=stu.rend();iter++)
cout<<iter->first<<' '<<iter->second<<endl;
(2).使用下标
map<string,int>stu;
stu.insert(pair<string,int>("bob",98));
stu.insert(map<string,int>::value_type ("laiu",89));
stu.insert(map<string,int>::value_type ("sakj",90));
stu["heelo"]=87;
cout<<stu["heelo"]; //只能通过key作为下标
4.删除
//使用迭代器进行删除
map<string,int>::iterator iter=stu.begin();
stu.erase(iter);
//使用关键字删除
stu.erase(key);
//删除一个范围
stu.erase(stu.begin(),stu.end()); //清空map,stu.clear();
5.查找
map<string,int>::iterator it;
it=stu.find(key); //寻找stu中关键字为key的数据,返回他的迭代器,没有找到就返回最后一个迭代器;
it=stu.lower_bound(key); //查找第一个大于等于key的数据
it=stu.upper_bound(key); //查找第一个大于key的数据
6.排序
//map本身已经具有排序功能,这里的排序针对的是key和value,如果key为结构体的话,由于没有定义<等符号的功能,就没办法进行排序,因此我们要自己定义
struct Student
{
string name;
int age;
bool operator<(const Student a)const
{
return name==a.name?age<a.age:name<a.name;
}
}
map<Student,int>list;
常用函数
.insert() 插入数据
.size() 当前的数据个数
.count(key) 计数key出现的个数,这个只能是0或者1
.begin() 返回第一个迭代器
.end() 返回最后一个迭代器
.empty() 判空
.find() 查找
.lower_bound()
.upper_bound()
.swap() 交换两个map的所有内容
.clear() 删除所有元素
参考博客