STL容器<unordered_map>

**一. 知识点:** 

  unordered_map是hash table 链表的一种。官方提供了这种容器,特点是无序。存储在桶中。

**二. 详解 :** 

//官方定义的结构体
template < class Key, class T, class Hash = hash<Key>, class Pred = equal_to<Key>, class Alloc = allocator< pair<const Key,T> > > class unordered_map;

Parameters

  • Key − Type of the key.

  • T − Type of the mapped values.

  • Hash − A unary function object type which takes an object of type key type as argument and returns a unique value of type size_t based on it.

  • Pred − A binary predicate that which two arguments of the key type and returns a bool.

  • Alloc − Type of the allocator object.

Member functions

  •   unordered_map::at() ->Returns a reference to the mapped value associated with key k.
  •   unordered_map::bucket_count() ->返回桶的数量。
  •   unordered_map::bucket_size() ->返回具体桶中的元素个数。
  •    unordered_map::equal(k) -> 返回与k值匹配的key,返回值的first为指向本身桶,second为指向下一个桶。而桶类型本身的也有first和second,分别代表key和value。 
  •    unordered_map::erase(const_iterator pos) ->void 返回值,擦除在pos的桶。
  •    unordered_map::erase(const_iterator first_pos,const_iterator last_pos) ->void 返回值,擦除从first_pos到last_pos的桶。
  •    unordered_map::load_factor() ->返回具体桶中的元素个数,等同于bucket_size()。
  • 具体用法请参考:https://www.tutorialspoint.com/cpp_standard_library/unordered_map.htm

 

  无序映射是类似于字典的数据结构。它是一个(键,值)对序列,每个唯一的键只关联一个值。它通常被称为关联数组。它可以根据键快速检索单个元素。它还实现了直接访问操作符(下标操作符[]),允许使用键值作为参数直接访问映射值。
无序映射(Unordered map)不会根据元素的键值或映射值以任何特定顺序排列元素,而是根据元素的哈希值将其组织成桶,以便根据键值直接快速访问单个元素。
在通过键值访问单个元素时,无序映射的性能优于映射。但对于范围迭代,它们的性能要低得多。范围迭代用array性能高。

**三. 运用  :  **

#include <iostream>
#include <unordered_map>

using namespace std;

int main(void) {
   unordered_map<char, int> um = {
            {'a', 1},
            {'b', 2},
            {'c', 3},
            };

   um.insert(pair<char, int>('d', 4));
   um.insert(pair<char, int>('e', 5));

   cout << "Unordered map contains following elements" << endl;

   for (auto it = um.begin(); it != um.end(); ++it)
      cout << it->first << " = " << it->second << endl;

   return 0;
}

  

 

posted @ 2023-07-16 23:31  Labant  阅读(98)  评论(0编辑  收藏  举报