在深入分析之前,先明确一点:unordered_map 和 unordered_set 的底层实现逻辑高度相似。它们都基于哈希表构建,封装过程大同小异。这篇我们直接切入核心细节,看看这两个容器在模板定义、迭代器行为以及插入操作上的具体表现。
1. unordered_map、unordered_set 的基本结构
虽然从接口上看,unordered_set 是键值对(K-K),而 unordered_map 是键值对(K-V),但在底层实现上,它们往往共用同一个哈希表模板。
unordered_set:
template<class K, class V>
class unordered_set {
struct SetKeyOfT {
const K& operator()(const K& key) { return key; }
};
public:
typedef typename hash_bucket::HashTable<K, K, SetKeyOfT>::const_iterator iterator;
typedef typename hash_bucket::HashTable<K, K, SetKeyOfT>::const_iterator const_iterator;
const_iterator begin() const { return _ht.begin(); }
const_iterator end() const { return _ht.end(); }
pair<const_iterator, bool> insert(const K& key) {
pair<typename hash_bucket::HashTable<K, K, SetKeyOfT>::iterator, bool> ret = _ht.Insert(key);
<const_iterator, >(ret.first, ret.second);
}
:
hash_bucket::HashTable<K, K, SetKeyOfT> _ht;
};


