C++ 11中已经引入了hash容器包括:
- unordered_set
- unordered_multiset
- unordered_map
- unordered_multimap
unordered_set的底层类hash_set的类声明为:
template <class _Value,
class _HashFcn __STL_DEPENDENT_DEFAULT_TMPL(hash<_Value>),
class _EqualKey __STL_DEPENDENT_DEFAULT_TMPL(equal_to<_Value>),
class _Alloc = __STL_DEFAULT_ALLOCATOR(_Value) >
class hash_set;
set的类声明为:
template <class _Key, class _Compare __STL_DEPENDENT_DEFAULT_TMPL(less<_Key>),
class _Alloc = __STL_DEFAULT_ALLOCATOR(_Key) >
class set;
注意hash容器与关联容器的区别:
-
hash容器是基于hash函数的,hash容器对相同元素的判断是基于相等,使用的排序规则默认为std::equal_to<>。其元素不是以排序方式存放的。
-
关联容器是基于红黑树的,对相同元素的判断基于等价,使用的排序规则默认为std::less<>。元素是基于排序存放的。