关于map,也就是字典,kv键值对。
在C++中,它是一个类模板,它是属于一个关联容器类模板
template < class Key, // map::key_type
class T, // map::mapped_type
class Compare = less
, // map::key_compare class Alloc = allocator
> // map::allocator_type > class map;
我们在新建map类型的时候,必须提供Key 和Value的类型,可选提供比较器和配置器,一般只是在使用自己的类型的时候,才需要提供。
map中,Key是唯一的,不能有多个相同的key,而且都是按照key的大小排序的,也就是说map都是自动排序的,
map里面的数据存储为pair
typedef pair
value_type;
常用的成员变量:
value_type;//pair
iterator;//迭代器,指向value_type const_iterator;//常量迭代器 reverse_iterator;//逆向迭代器 const_reverse_iterator;//常量,逆向
常用的成员函数:
//1. 迭代器
begin();
end();
rbegin();
rend();
cbegin();//以下C++11新加入
cend();
crbegin();
crend();
//以上都是返回迭代器,其中r开头的表示返回的是逆向的迭代器,c开头的表示返回的是const迭代器。
//2. 容量:
empty();//测试map是否为空
size();//返回容器的大小;
//3. 获取元素
operator[];//可以像普通的数组一样的方式使用。
at(const key_type& k);//C++11新加方法。
//4. 增删改查
insert(const value_type& val);//增
erase(iterator position);//删
size_type erase (const key_type& k);//删
void erase (iterator first, iterator last);//删
clear();//删除所有的数据。
find (const key_type& k);//查
count (const key_type& k);//与find有点功能重复,因为map的key是唯一的,所以count只能返回两个值,0或者1,分别表示存在这个key或者不存在。
字典应该是平时编程中很经常用到的一个数据结构。比如,有时候需要计算一篇文章中的每个单词出现的次数,以形成文章的词向量。
#include
#include