C++ STL中,哈希表
对应的容器是 unordered_map
(since C++ 11)。
定义
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;
- 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.
unordered_map的原理
hashtable + bucket
由于 unordered_map 内部采用 hashtable 的数据结构存储,所以,每个特定的 key 会通过一些特定的哈希运算映射到一个特定的位置,我们知道,hashtable 是可能存在冲突的,在同一个位置的元素会按顺序链在后面(也就是使用拉链法解决哈希冲突)。所以把这个位置称为一个 bucket 是十分形象的,每个哈希桶中可能没有元素,也可能有多个元素。
unordered_map的插入过程:
1、得到 key;
2、通过 hash 函数得到 key对应的 hash 值;
3、得到桶号&