std::unordered_map

template < class Key,                                    // unordered_map::key_type
class T, // unordered_map::mapped_type
class Hash = hash<Key>, // unordered_map::hasher
class Pred = equal_to<Key>, // unordered_map::key_equal
class Alloc = allocator< pair<const Key,T> > // unordered_map::allocator_type
> class unordered_map;

Unordered Map

Unordered maps are associative containers that store elements formed by the combination of a key value and a mapped value, and which allows for fast retrieval of individual elements based on their keys.

In an unordered_map, the key value is generally used to uniquely identify the element, while the mapped value is an object with the content associated to this key. Types of key and mapped value may differ.

Internally, the elements in the unordered_map are not sorted in any particular order with respect to either their key or mapped values, but organized into buckets(桶) depending on their hash values to allow for fast access to individual elements directly by their key values (with a constant average time complexity on average).

unordered_map containers are faster than map containers to access individual elements by their key, although they are generally less efficient for range iteration through a subset of their elements.

Unordered maps implement the direct access operator (operator[]) which allows for direct access of the mapped value using its key value as argument.

Iterators in the container are at least forward iterators.

Container properties

  • Associative Elements in associative containers are referenced by their key and not by their absolute position in the container.
  • Unordered Unordered containers organize their elements using hash tables that allow for fast access to elements by their key.
  • Map Each element associates a key to a mapped value: Keys are meant to identify the elements whose main content is the mapped value.
  • Unique keys No two elements in the container can have equivalent keys.
  • Allocator-aware The container uses an allocator object to dynamically handle its storage needs.

Template parameters

  • Key

    Type of the key values. Each element in an unordered_map is uniquely identified by its key value.

    Aliased as member type unordered_map::key_type.

  • T

    Type of the mapped value. Each element in an unordered_map is used to store some data as its mapped value.

    Aliased as member type unordered_map::mapped_type. Note that this is not the same as unordered_map::value_type (see below).

  • Hash

    A unary(一元) function object type that takes an object of type key type as argument and returns a unique value of type size_t based on it. This can either be a class implementing a function call operator or a pointer to a function (see constructor for an example). This defaults to hash, which returns a hash value with a probability of collision approaching 1.0/std::numeric_limits<size_t>::max().

    The unordered_map object uses the hash values returned by this function to organize its elements internally, speeding up the process of locating individual elements.

    Aliased as member type unordered_map::hasher.

  • Pred

    A binary predicate(断言) that takes two arguments of the key type and returns a bool. The expression pred(a,b), where pred is an object of this type and a and b are key values, shall return true if a is to be considered equivalent to b. This can either be a class implementing a function call operator or a pointer to a function (see constructor for an example). This defaults to equal_to, which returns the same as applying the equal-to operator (a==b).

    The unordered_map object uses this expression to determine whether two element keys are equivalent. No two elements in an unordered_map container can have keys that yield true using this predicate.

    Aliased as member type unordered_map::key_equal.

  • Alloc

    Type of the allocator object used to define the storage allocation model. By default, the allocator class template is used, which defines the simplest memory allocation model and is value-independent.

    Aliased as member type unordered_map::allocator_type.

In the reference for the unordered_map member functions, these same names (Key, T, Hash, Pred and Alloc) are assumed for the template parameters.

Iterators to elements of unordered_map containers access to both the key and the mapped value. For this, the class defines what is called its value_type, which is a pair class with its first value corresponding to the const version of the key type (template parameter Key) and its second value corresponding to the mapped value (template parameter T):

typedef pair<const Key, T> value_type;

Iterators of a unordered_map container point to elements of this value_type. Thus, for an iterator called it that points to an element of a map, its key and mapped value can be accessed respectively(分别) with:

unordered_map<Key,T>::iterator it;
(*it).first; // the key value (of type Key)
(*it).second; // the mapped value (of type T)
(*it); // the "element value" (of type pair<const Key,T>)

Naturally, any other direct access operator, such as -> or [] can be used, for example:

it->first;               // same as (*it).first   (the key value)
it->second; // same as (*it).second (the mapped value)

Member types

The following aliases are member types of unordered_map. They are widely used as parameter and return types by member functions:

member type definition notes
key_type the first template parameter (Key)
mapped_type the second template parameter (T)
value_type pair<const key_type,mapped_type>
hasher the third template parameter (Hash) defaults to: hash<key_type>
key_equal the fourth template parameter (Pred) defaults to: equal_to<key_type>
allocator_type the fifth template parameter (Alloc) defaults to: allocator<value_type>
reference Alloc::reference
const_reference Alloc::const_reference
pointer Alloc::pointer for the default allocator: value_type*
const_pointer Alloc::const_pointer for the default allocator: const value_type*
iterator a forward iterator to value_type
const_iterator a forward iterator to const value_type
local_iterator a forward iterator to value_type
const_local_iterator a forward iterator to const value_type
size_type an unsigned integral type usually the same as size_t
difference_type a signed integral type usually the same as ptrdiff_t

Member functions

  • (constructor) Construct unordered_map (public member function )
  • (destructor) Destroy unordered map (public member function)
  • operator= Assign content (public member function )

Capacity

  • empty Test whether container is empty (public member function)
  • size Return container size (public member function)
  • max_size Return maximum size (public member function)

Iterators

  • begin Return iterator to beginning (public member function)
  • end Return iterator to end (public member function)
  • cbegin Return const_iterator to beginning (public member function)
  • cend Return const_iterator to end (public member function)

Element access

  • operator[] Access element (public member function )
  • at Access element (public member function)

Element lookup

  • find Get iterator to element (public member function)
  • count Count elements with a specific key (public member function )
  • equal_range Get range of elements with specific key (public member function)

Modifiers

  • emplace Construct and insert element (public member function )
  • emplace_hint Construct and insert element with hint (public member function )
  • insert Insert elements (public member function )
  • erase Erase elements (public member function )
  • clear Clear content (public member function )
  • swap Swap content (public member function)

Buckets

  • bucket_count Return number of buckets (public member function)
  • max_bucket_count Return maximum number of buckets (public member function)
  • bucket_size Return bucket size (public member type)
  • bucket Locate element's bucket (public member function)

Hash policy

  • load_factor Return load factor (public member function)
  • max_load_factor Get or set maximum load factor (public member function )
  • rehash Set number of buckets (public member function )
  • reserve Request a capacity change (public member function)

Observers

  • hash_function Get hash function (public member type)
  • key_eq Get key equivalence predicate (public member type)
  • get_allocator Get allocator (public member function)

Non-member function overloads

  • operators (unordered_map) Relational operators for unordered_map (function template )
  • swap (unordered_map) Exchanges contents of two unordered_map containers (function template )

Code Example

#include <iostream>
#include <string>
#include <unordered_map> using namespace std; typedef unordered_map<string,string> stringmap;
typedef unordered_map<int,int> intmap; stringmap merge(stringmap a,stringmap b){
stringmap tmp(a);
tmp.insert(b.begin(),b.end());
return tmp;
} int main(int argc, char **argv)
{
stringmap first1;
stringmap first2( { {"apple","red"}, {"lemon","yellow"} } );
stringmap first3( { {"orange","orange"}, {"strawberry","red"} } );
stringmap first4( first2 );
stringmap first5( merge(first2, first3) );
stringmap first6( first5.begin(), first5.end() ); cout << "string map first6 :\n";
for( auto& x:first6 )
cout << x.first << ":" << x.second << "\n"; stringmap second = { {"house","maison"}, {"apple","pomme"}, {"tree","arbre"},
{"book","liver"}, {"door","porte"}, {"grapefruit","pamplemouse"} }; unsigned n = second.bucket_count();
cout << "\nsecond map has " << n << " buckets\n";
for( unsigned i=0; i < n; i++ ){
cout << "bucket#" << i << "contains: "<< second.bucket_size(i) << "elements: ";
for( auto it = second.begin(i); it != second.end(i); it++ ){
cout << it->first << ":" << it->second << ",";
}
cout << "\n";
} cout << "\n";
for( auto& x:second){
cout << "Element [" << x.first << ":" << x.second << "]";
cout << " is in bucket #" << second.bucket( x.first ) << "\n";
} intmap third; cout << "size: " << third.size() << "\n";
cout << "bucket_count: " << third.bucket_count() << "\n";
cout << "load_factor: " << third.load_factor() << "\n";
cout << "max_load_factor: "<< third.max_load_factor() << "\n"; /**
* Sets the number of buckets in the container to n or more.
If n is greater than the current number of buckets in the container (bucket_count), a rehash is forced. The new bucket count can either be equal or greater than n.
If n is lower than the current number of buckets in the container (bucket_count), the function may have no effect on the bucket count and may not force a rehash.
*/ third.rehash(40);
cout << "rehash bucket count: "<< third.bucket_count() << "\n"; intmap::hasher fn = third.hash_function();
cout << "int hash function: 10:" << fn(10) << "\n";
cout << "int hash function: 11:" << fn(11) << "\n"; return 0;
}

Reference

cplusplus


C++ std::unordered_map的更多相关文章

  1. C++ std::unordered_map使用std::string和char *作key对比

    最近在给自己的服务器框架加上统计信息,其中一项就是统计创建的对象数,以及当前还存在的对象数,那么自然以对象名字作key.但写着写着,忽然纠结是用std::string还是const char *作ke ...

  2. C++11中std::unordered_map的使用

    unordered map is an associative container that contains key-value pairs with unique keys. Search, in ...

  3. hashmap C++实现分析及std::unordered_map拓展

    今天想到哈希函数,好像解决冲突的只了解了一种链地址法而且也很模糊,就查了些资料复习一下 1.哈希Hash 就是把任意长度的输入,通过哈希算法,变换成固定长度的输出(通常是整型),该输出就是哈希值. 这 ...

  4. 记一个关于std::unordered_map并发访问的BUG

    前言 刷题刷得头疼,水篇blog.这个BUG是我大约一个月前,在做15445实现lock_manager的时候遇到的一个很恶劣但很愚蠢的BUG,排查 + 摸鱼大概花了我三天的时间,根本原因是我在使用s ...

  5. std::unordered_map

    map与unordered_map的区别 1.map: map内部实现了一个红黑树,该结构具有自动排序的功能,因此map内部的所有元素都是有序的,红黑树的每一个节点都代表着map的一个元素, 因此,对 ...

  6. std::unordered_map与std::map

    前者查找更快.后者自动排序,并可指定排序方式. 资料参考: https://blog.csdn.net/photon222/article/details/102947597

  7. STL: unordered_map 自定义键值使用

    使用Windows下 RECT 类型做unordered_map 键值 1. Hash 函数 计算自定义类型的hash值. struct hash_RECT { size_t operator()(c ...

  8. C++11 新特性: unordered_map 与 map 的对比

    unordered_map和map类似,都是存储的key-value的值,可以通过key快速索引到value.不同的是unordered_map不会根据key的大小进行排序, 存储时是根据key的ha ...

  9. map 与 unordered_map

    两者效率对比: #include <iostream> #include <string> #include <map> #include <unordere ...

随机推荐

  1. CSS内容简单归纳

    具体内容请查阅<CSS参考手册> 一.CSS模块介绍 1.1 CSS1中定义了网页基本属性 字体.颜色.补白.基本选择器等 1.2 CSS2中在CSS1的基础上添加了高级功能 浮动和定位. ...

  2. angular-ui-bootstrap弹出框的使用(一)

    在开发项目时,我们经常性的会遇到弹出框的需求,例如登陆,注册,添加信息等等....面对这一需求,我们当然也可以使用自己的双手进行编写,如果你时间充足可以试试. 今天我们讲解一下如何在angular框架 ...

  3. k-means算法Java一维实现

    这里的程序稍微有点变形.k_means方法返回K-means聚类的若干中心点.代码: import java.util.ArrayList; import java.util.Collections; ...

  4. net start mongodb发生系统错误2 系统找不到指定的文件

    安装mongodb时, 将mongodb 作为系统服务启动 net start mongodb,报错发生系统错误2 系统找不到指定的文件 . 查找原因是因为,系统服务的可执行文件地址有误. 修改服务地 ...

  5. TCP/IP网络编程系列之三(初级)

    TCP/IP网络编程系列之三-地址族与数据序列 分配给套接字的IP地址和端口 IP是Internet Protocol (网络协议)的简写,是为首发网络数据而分配给计算机的值.端口号并非赋予计算机值, ...

  6. 「自己开发直播」实现nginx-rtmp-module多频道输入输出与权限控制

    之前写了一篇文章,利用nginx和nginx-rtmp-module实现直播. 不过,之前只是做到了能够直播而已,只能一个人推流,并没有实现多人多频道输入输出,也没有权限控制,只要知道rtmp的URL ...

  7. Appium+python自动化27-等待activity出现(android特有的wait_activity)

    前言 在启动app的时候,如果直接做下一步点击操作,经常会报错,于是我们会在启动完成的时候加sleep. 那么问题来了,这个sleep时间到底设置多少合适呢?设置长了,就浪费时间,设置短了,就会找不到 ...

  8. .NET System.Web.HttpContext.Current.Request报索引超出数组界限。

    移动端使用Dio发送 FormData, 请求类型 multipart/form-data, FormData内可以一个或多个包含文件时. 请求接口时获取上传的fomdata数据使用 System.W ...

  9. 2017百度之星初赛B-1002(HDU-6115)

    一.思路 这题“看似”比较难搞的一点是,一个节点上有多个办公室,这怎么求?其他的,求树中任意两个节点的距离(注意:没有最远或最最进这一说法,因为树上任意两个节点之间有且仅有一条路径.不然就有回路了,对 ...

  10. Thread pools & Executors

    Thread pools & Executors Run your concurrent code in a performant way All about thread pools # H ...