map:键值保存,高效访问
通过键值来排序,通过键值来查找
高效访问:1000个数据只要查找1-10次,100万个数据只要1-20次就可以查找到。
2^n > 数据总数即可
可以看得出map对处理大数据有用
插入效率低于链表,因为涉及到排序。
map的应用:红黑树——一种平衡排序二叉树
1.map的构造函数
(1)无参构造:
map<int,char> mp;//<键值,实值>,因为要排序,所以要合理选取键值的类型。
(2)一个参数:用一个map给另个map初始化
map<int,char> mp2(mp1);
(3)用另个map中的一段对当前map进行初始化
map<int,char> mp3(mp2.begin(),mp2.end());//要想要中间的,进行++,- -
2.插入操作
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
void fun(pair<int,char> pr)
{
cout<<" "<<pr.first<<" "<<pr.second<<endl;
}
void MapConstruct()
{
typedef pair<int,char> in_pair;//重命名,方便输入
map<int ,char> mp;
第一种插入方式
mp.insert(in_pair(1,'a'));
mp.insert(in_pair(3,'b'));
mp.insert(pair<int,char>(2,'c'));
mp.insert(pair<int,char>(4,'d'));
mp.insert(pair<int,char>(5,'e'));
mp.insert(pair<int,char>(8,'g'));
无论我们按什么顺序输入,他的输出都是按照键值排序输出的
第二种插入方式
map<int,char>::iterator iter = mp.begin();//创建迭代器,迭代器可以进行++操作,但不可以执行+4.
iter++;
iter++;
iter++;
iter++;
mp.insert(iter,in_pair(6,'f'));//虽然改变了iter的位置,但是输出时依旧按照键值进行排序(附图)
第三种插入方式:整段插入
map<int,char> mp1;
mp1.insert(in_pair(11,'j'));
mp1.insert(mp.begin(),mp.end());
for_each(mp.begin(),mp.end(),fun);
for_each(mp1.begin(),mp1.end(),fun);//包含于头文件algorithm,用于输出
}
int main()
{
MapConstruct();
return 0;
}
3.一些其他属性
(1)map没有容量
(2)size():得到元素的个数
(3)count(键值):判断某个键值是否存在
(4)empty():判断map是否为空,非空为 1.
(5)头尾迭代器
map<int,char>::iterator iter = mp.begin();
for(iter;iter!=mp.end(),iter++)
{
cout<<iter->first<<" "<<iter->second<<endl;
}
4.其他操作
(1)键值不可以修改,实值可以修改
(2)输出:第一可以使用for_each,第二个可以使用迭代器(上述的头尾迭代器)
(3)删除:
第一种:删除一个元素
map<int,char>::iterator iter = mp.begin();
iter++;
iter++;
mp.erase(iter);
第二种:删除一个区间
map<int,char>::iterator iter = mp.begin();
iter++;
iter++;
mp.erase(iter,mp.end());
第三种:按照键值删除
mp.erase(3);//删除键值3的记录
(4)查找:按照键值查找
map<int,char>::iterator iter = mp.begin();
map<int,char>::iterator iter1 = mp.find(2);//find函数的返回值是迭代
cout<<iter1->first<<" "<<iter1->second<<endl;
(5)改变顺序:默认的是从小到大的顺序,可以改变成从大到小的顺序
map<int,char,greater> mp;
但是需要头文件#include
(6)如果查找find未找到这个元素时,系统就会直接崩溃,处理方法:
lower_bound(key):返回的键值不小于这个键值:如果有key,则返回key,否则返回第一个大于key的键值
upper_bound(key):返回的键值是第一个大于key的键值
equal_range(key):返回的是pair类型,是上述两个的区间。