Map
map是一个stl的容器
我们可以理解为map是一个强大的动态数组,他的下标可以是任意的数据类型
如何来定义它呢?
比如:
map<int,int>mp;
或者用式子来打比方:
map<下表类型,数据类型>变量名
map会将他存储的所有数据按照下标从小到大排序
map不能存在多个相同的下标
map插入、查询、删除都是log(mp.size());
接着看map的插入
map插入一个元素:
如果mp中已经有x了,那么mp[x] = 1,会直接赋值
map[x]=x;//这样可以建一个下标为x的元素,默认为0,然后设值为x
mp[x] ++; // 这样也是插入一个元素, 先创建下标为x的元素,默认为0,然后加1
在使用map时,都会优先去寻找是否存在下标,包括赋值,删除,然后再进行操作
接着如何访问下标
并不是if(mp[x] == 0) // 这样也是插入
而是这样:
if(mp.count(x))
// mp.count(x)就会计算x这个下标是否存在,存在返回1,不存在返回0
接着map如何删除某个下标
mp.erase(x); // 删除的是x这个下标
如何清空map
mp.clear();
获取map中元素的个数(下标的个数)
mp.size();
map二分查找lower_bound
map<int, int>mp; // 定义了一个下标类型为int,值类型为int的map
// 在mp中二分查询第一个大于等于x的下标,
但是lower_bound返回的是地址,而在stl容器中或者说是在map中,
他返回的是迭代器(一个属于map的下标,在map中他将地址进行了封装)
// 在这里我们接受lower_bound返回值的之后,我们是定义了一个map<int,int>::iterator it的迭代 器,我们可以把他理解为地址
// 注意不同类型的map他的迭代器是不同的
// 例如map<string, int>mp; 他的迭代器定义: map<string, int>::iterator it;
// 定义了一个迭代器,变量名叫it map<int,int>::iterator it = mp.lower_bound(x);
// 这样就可以在map中查询大于等于x的第一个下标
// 如果map中不存在大于等于x的数字,那么it最终等于mp.end(),指向终止位置+1
在map中如果获得了迭代器,那么map一个元素其实是一个<下标,值>的数据对下标存在第一个位置,而值存在第二个位置
所以通过迭代器获取下标,it->first
通过迭代器获取值,it->second
如果map中不存在大于等于x的数字,那么it最终等于mp.end(),指向终止位置+1
map<int,int>::iterator it = mp.upper_bound(x);
这样就可以在map中查询大于x的第一个下标
#include <bits/stdc++.h>
using namespace std;
map<int,int>mp;
int main()
{
mp[2] = 1;
mp[3] = 2;
mp[7] = 3;
mp[8] = 4;
// 定义类一个map<int,int>::iterator 类型的变量名字叫it
map<int,int>::iterator it = mp.upper_bound(6);
// 二分查询大于6的第一个下标
// 通过下标或者迭代器获取这个里面的值
cout << it->first << " " << it->second;
// 输出第一个大于等于6的下标,以及他里面存储的值
return 0;
}
map的遍历
map是不连续的,所以不能通过下标来遍历
那map使用什么遍历的呢
它是通过迭代器来遍历的
map的起始地址是mp.begin()
然后map终止地址的后一个是mp.end();
#include <bits/stdc++.h>
using namespace std;
map<int,int>mp;
int main()
{
mp[7] = 3;
mp[10] = 5;
mp[2] = 1;
mp[4] = 2;
for(map<int,int>::iterator it = mp.begin(); it != mp.end(); it ++)
{
cout << it->first << " " << it->second << endl;
// 遍历map中所有的下标以及他的值
}
return 0;
}