赞
踩
有一段时间没有继续进行C++容器的学习了。这次接着C+±std::Vector 的内容继续学习。通过之前的vector的学习,我发现虽然对该容器有一个比较全面的认识,但是很多细节还是不能注意好。比如在 LeetCode-406. Queue Reconstruction by Height 这道题中使用vector的insert函数,而我之前的方法由于没有把握好erase函数的使用特点,这道题没有顺利解决。所以在map学习中,将更加注重容器的特性与函数的运用方法与结果特点。
STL map微软官方文档翻译为“映射”,map是一种关联容器,按照特定顺序存储由键值和映射值组合形成的元素。map提供一个键值对容器,它提供了很好一对一的关系,它的特点是增加和删除节点对迭代器的影响很小,除了那个操作节点,对其他的节点都没有什么影响。对于迭代器来说,可以修改实值,而不能修改key。
map可以自动建立Key - value(键值对)的对应。key 和 value可以是任意你需要的类型。 根据key值快速查找记录,查找的复杂度基本是Log(N),如果有1000个记录,最多查找10次,1,000,000个记录,最多查找20次。可以 快速插入Key - Value 记录、 快速删除记录。根据Key 修改value记录。 遍历所有记录。 使用map需要引入头文件:
#include <map> //注意,STL头文件没有扩展名.h
这一点在我之前的vector总结中有误,已经更正。map语法表达如下:
template <
class Key,
class Type,
class Compare = less<Key>,
class Allocator=allocator<pair <const Key, Type>>>
class map;
其中:
1.构造一个空的map:
map <int, int> m0; //键值对类型为int,int
2.构造一个空map,指定排序键类型less than,并插入4个元素:
typedef pair <int, int> Int_Pair;
map <int, int, less<int> > m1; //注意这里的两个>符号,最好有一个空格,不然会误认为>>
m1.insert(Int_Pair(1, 10));
m1.insert(Int_Pair(2, 20));
m1.insert(Int_Pair(3, 30));
m1.insert(Int_Pair(4, 40));
3.构造一个空map,指定排序键类型greater than,并插入2个元素:
map <int, int, greater<int> > m2;
m2.insert(Int_Pair(1, 10));
m2.insert(Int_Pair(2, 20));
这个地方微软文档记录有误,我顺手改了过来。关于greater< int >与less< less >可以参考这篇文档:greater()和less()的使用。
4.利用m1的分配器构造m3:
map <int, int>::allocator_type m1_Alloc;
m1_Alloc = m1.get_allocator();
map <int, int> m3(less<int>(), m1_Alloc);
m3.insert(Int_Pair(3, 30));
5.通过拷贝m1创建m4:
map <int, int> m4(m1);
6.通过拷贝m1的first到last区域的内容创建m5:
map <int, int>::const_iterator m1_bcIter, m1_ecIter;
m1_bcIter = m1.begin();
m1_ecIter = m1.begin();
m1_ecIter++; m1_ecIter++;
map <int, int> m5(m1_bcIter, m1_ecIter);
7.拷贝初值链表的方式创建map:
map<int, int> m8{ { { 1, 1 }, { 2, 2 }, { 3, 3 },
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。