Maps are associative containers that store elements formed by a combination of a key value and a mapped value, following a specific order.
map是关联容器,它以某种顺序存储元素,每个元素都是一个键值key value和它映射值mapped value的组合。

In a map, the key values are generally used to sort and uniquely identify the elements, while the mapped values store the content associated to this key. The types of key and mapped value may differ, and are grouped together in member type value_type, which is a pair type combining both:
在map中,一般用key值对元素排序和唯一标识元素,映射值存储与该键关联的内容。key value和mapped value的类型可能不同,并以成员的方式组合在一起,也即使用pair类型组合。

typedef pair value_type;


Internally, the elements in a map are always sorted by its key following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare).
在内部,map中的元素总是按照内部比较对象(类型为Compare)指示的一种严格弱排序标准,按照key排序。

map containers are generally slower than unordered_map containers to access individual elements by their key, but they allow the direct iteration on subsets based on their order.
map容器在通过key访问单个元素时一般比unordered_map容器慢,但允许基于其顺序对子集直接迭代。

The mapped values in a map can be accessed directly by their corresponding key using the bracket operator ((operator[]).
map中的映射值可以通过key用[]直接访问。

Maps are typically implemented as binary search trees.
map通常用二叉搜索树实现。

插值或改值 []=

  1. std::map<char,int> first;
  2. first['x']=8; // 增加元素 <'x', 8>
  3. first['x']=16; // 修改元素 <'x', 8> -> <'x', 16>

取值 []或at

  1. mapped_type& operator[] (const key_type& k);
  2. /* 如果键k在map中存在,则返回对应映射值的引用;
  3. 如果无对应键k,则会向map中新增以k为key的元素,
  4. 对应映射值的初始化使用默认构造器。
  5. */
  6. mapped_type& at (const key_type& k);
  7. const mapped_type& at (const key_type& k) const;
  8. /* at()也可以用于取键k的映射值,但在当map中无键k时,会抛出out_of_range的异常。
  9. */

查找元素是否存在 find、count

  1. iterator find (const key_type& k);
  2. const_iterator find (const key_type& k) const;
  3. /* 在容器中搜索键为k的元素,找到了返回迭代器,找不到返回map::end()。
  4. 返回的迭代器是指向元素(类型为value_type)的bidirectional iterator。
  5. 注意map的value_type是pair<const key_type, mapped_type>,
  6. 也就是返回的迭代器的first等于元素的key value,second等于元素的mapped value
  7. */
  8. size_type count (const key_type& k) const;
  9. /* 在容器中搜索键为k的元素的个数,由于map中键具有唯一性,
  10. 因此当map中不存在键k时,返回0;存在键k时返回1。
  11. */

删除元素 erase

  1. iterator erase (const_iterator position); // 1
  2. size_type erase (const key_type& k); // 2
  3. iterator erase (const_iterator first, const_iterator last); // 3
  4. /* 1、2根据迭代器或键删除指定元素
  5. 3根据迭代器范围删除[fist, last)内的元素。
  6. 返回的迭代器指向被删除的最后一个元素之后的元素,或者为map::end
  7. 被删除的元素的会被摧毁(destroy)。
  8. */

查找最小、最大的键值 begin\rbegin

  1. // map中按键对元素排序(默认升序)
  2. // 最小键值
  3. iterator begin() noexcept;
  4. const_iterator begin() const noexcept;
  5. /* 返回指向map中第一个元素的迭代器(map为空时会得到一个默认值)*/
  6. // 最大键值
  7. reverse_iterator rbegin() noexcept;
  8. const_reverse_iterator rbegin() const noexcept;
  9. /* 返回指向map中最后一个元素的迭代器(map为空时会出错)
  10. 迭代器从rbegin()到rend()与从begin()到end()一样,也是++,因为是reverse_iterator
  11. */