Map进阶:
Map在c++中的定义
map是一个stl容器
他是一个下标可以是任意的数据类型的vector
map<下标类型,值的类型>
map会将他存储的所有数据按照下标从小到大排序
每种下标都只有一个
Map的插入
查询,赋值,更改都是插入
mp[x]=1
这是赋值
mp[x]++
这是更改
if(mp[x]==1)
这是查询
在map中,不管是查询、赋值、更改,map都会先查询他是否存在这个下标,如果不存在,则建立这个下标,并且赋初始值0。如果存在,不用重新创建,直接对他进行操作
map怎么查询是否存在某个下标
代码mp.count(x);
//这个函数会查询map中是否存在x这个下标
//存在返回1,否则返回0
map删除下标
代码mp.erase(x); // 删除map中x这个下标与x的值
清空map
代码mp.clear();
获取map中元素的个数
代码mp.size();
//有几个下标就返回几
map二分查找
lower_bound():
在mp中二分查找第一个大于等于x的下标,但是lower_bound返回的是地址,而在stl容器(map是其中之一)中,他返回的是迭代器
迭代器就是一个被封装过的地址
lower_bound返回值之后,我们定义了一个map<int,int>::iterator it的迭代器
(map<int,int>::iterator是一个数据类型,it是这个迭代器的名字)
不同类型的map他的迭代器是不同的
下标类型为string的map需要在定义一个迭代器
C++map<int,int>::iterator it=mp.lower_bound(x);
这样就可以在map中查询大于等于x的第一个下标
但如果map中不存在大于等于x的数字,那么it最终等于终止位置+1
我们最终获取的迭代器是一个数对(下标,值)
通过迭代器获取下标,it->first
通过迭代器获取值,it->second
C++map<int,int>mp;
mp[1]=6
mp[7]=5;
mp[2]=3;
mp[10]=9;
map<int,int>::iterator it=lower_bound(6);
cout<<it->first<<" "<<it->second;
upper_bound():
C++map<int,int>::iterator it=mp.upper_bound(x);
这样就可以在map中查询小于等于x的最后一个下标
C++map<int,int>mp;
mp[1]=6
mp[7]=5;
mp[2]=3;
mp[10]=9;
map<int,int>::iterator it=upper_bound(9);
cout<<it->first<<" "<<it->second;
map的遍历:
map的下标是不连续的,所以不能通过直接枚举下标来遍历
map是通过迭代器来遍历的
map的起始地址(起始迭代器)= mp.begin()
map的终止地址(终止迭代器)+1 = mp.end();
C++map<int,int>mp;
mp[1]=6
mp[7]=5;
mp[2]=3;
mp[10]=9;
for(map<int,int>::iterator it=mp.begin();it!=mp.end();it++){
cout<<it->first<<" "<<it->second;
}
map范围遍历:
map范围遍历必须在c++11及以上版本使用
因为我们需要使用在c++11以后开发出的一个关键字——auto
他就是要计算机帮我们识别应该定义成什么数据类型
这样使用范围遍历,会从起始位置开始遍历到终止位置结束
C++map<int,int>mp;
mp[1]=6
mp[7]=5;
mp[2]=3;
mp[10]=9;
for(auto v:mp){
cout<<v.first<<" "<<v.second;
}