介绍
unordered_set
是一个封装哈希表的无序容器,其中每个元素仅可出现一次。
unordered_multiset
是一个封装哈希表的无序容器,其中每个元素可出现任意次。
unordered_set
和 unordered_multiset
均定义于头文件 <unordered_set>
中,各自声明如下:
template<
class Key,
class Hash = std::hash<Key>,
class KeyEqual = std::equal_to<Key>,
class Allocator = std::allocator<Key>
> class unordered_set;
template<
class Key,
class Hash = std::hash<Key>,
class KeyEqual = std::equal_to<Key>,
class Allocator = std::allocator<Key>
> class unordered_multiset;
到这里可能有一个问题:
set
和unordered_set
/multiset
和unordered_set
应该使用哪一种 (关联式容器和无序容器应该使用哪一种)?
考虑一个容器好坏,有一个标准是查看插入元素和查询元素的复杂度。
对于顺序容器,往往是插入复杂度高,查询复杂度低;又或者插入复杂度低,查询复杂度高,两者不能兼顾。
对于关联式容器,通过基于树结构,可以实现插入和查询都具有不太高的复杂度,而且其中元素是有序的。
对于无序容器,通过线性+链表,可以使得插入和查询复杂度更低,但是元素顺序会被打乱。从上面的比较可以看出,在选择关联式容器和无序容器时,如果题目不涉及有序问题,应优先使用无序容器。
unordered_set
和 unordered_multiset
都是基于哈希表实现的,而且冲突策略采用的是链地址法。示意图如下:
如图所示,容器每一行都是一条链,在unordered_set
和 unordered_multiset
中称其为一个桶,