跳到主要内容C++ unordered 容器使用与模拟实现笔记 | 极客日志C++
C++ unordered 容器使用与模拟实现笔记
详细对比了 unordered_set/unordered_map 与 set/map 的差异,包括键值要求(哈希+判等 vs. 小于比较)、迭代器有序性及性能(平均 O(1) vs. O(logN))。然后基于哈希表逐步模拟实现了自己的 unordered_set 和 unordered_map,涵盖开放链地址法的哈希表、单向迭代器(含 operator++ 跨桶)、通过 KeyOfT 仿函数复用同一哈希表模板,以及 operator[] 等关键细节,完整给出了 zlr 命名空间下的实现代码。
橘子海3 浏览 STL 里的 unordered_set 和 unordered_map 底层是哈希表,它们和红黑树实现的 set/map 长得像,但行为细节不同。
与 set/map 的差异
unordered_set 要求 key 能转成整形并支持判等,而不是小于比较——这由哈希表决定。迭代器是单向的,遍历起来无序(哈希桶顺序),但 set 的迭代器是双向的有序遍历。多数场景下,unordered 版本增删查更快,平均 O(1) vs. 红黑树的 O(logN)。下面这段代码可以让你直观感受一下:
#include<unordered_set>
#include<set>
#include<iostream>
using namespace std;
int test_set2() {
const size_t N = 1000000;
unordered_set<int> us;
set<int> s;
vector<int> v;
v.reserve(N);
srand(time(0));
for (size_t i = 0; i < N; ++i) {
v.push_back(rand() + i);
}
size_t begin1 = clock();
for (auto e : v) { s.insert(e); }
size_t end1 = clock();
cout << "set insert:" << end1 - begin1 << endl;
size_t begin2 = clock();
us.reserve(N);
for (auto e : v) { us.insert(e); }
end2 = ();
cout << << end2 - begin2 << endl;
m1 = ;
begin3 = ();
( e : v) {
ret = s.(e);
(ret != s.()) { ++m1; }
}
end3 = ();
cout << << end3 - begin3 << << m1 << endl;
m2 = ;
begin4 = ();
( e : v) {
ret = us.(e);
(ret != us.()) { ++m2; }
}
end4 = ();
cout << << end4 - begin4 << << m2 << endl;
cout << << s.() << endl;
cout << << us.() << endl << endl;
begin5 = ();
( e : v) { s.(e); }
end5 = ();
cout << << end5 - begin5 << endl;
begin6 = ();
( e : v) { us.(e); }
end6 = ();
cout << << end6 - begin6 << endl << endl;
;
}
{
();
;
}
size_t
clock
"unordered_set insert:"
int
0
size_t
clock
for
auto
auto
find
if
end
size_t
clock
"set find:"
"->"
int
0
size_t
clock
for
auto
auto
find
if
end
size_t
clock
"unordered_set find:"
"->"
"插入数据个数:"
size
"插入数据个数:"
size
size_t
clock
for
auto
erase
size_t
clock
"set erase:"
size_t
clock
for
auto
erase
size_t
clock
"unordered_set erase:"
return
0
int main()
test_set2
return
0
unordered_map 和 map 同理,额外支持 operator[]。至于 unordered_multiset/unordered_multimap,就是允许 key 重复的版本,差异同上。
一些和哈希桶、负载因子相关的接口(bucket_count, load_factor, rehash 等)平时用得不多,了解就行。
| Buckets 接口 | 说明 |
|---|
| bucket_count | 返回容器中的桶数量 |
| max_bucket_count | 返回容器可以拥有的最大桶数 |
| bucket_size | 返回桶 n 中的元素数量 |
| bucket | 返回元素值 k 所在的桶号 |
| Hash policy 接口 | 说明 |
|---|
| load_factor | 返回容器中的当前负载因子 |
| max_load_factor | 获取或设置最大负载因子 |
| rehash | 将容器中的桶数量设置为 n 或更多,强制执行重新散列。当容器的负载因子即将超过其最大负载因子时,容器会自动执行 rehash。此函数需要桶的数量作为参数。 |
| reserve | 将容器中的桶数量(bucket_count)设置为最适合至少包含 n 个元素的数量。如果 n 大于当前 bucket_count 乘以 max_load_factor,则容器中的 bucket_count 会增加,并强制进行重新哈希。 |
底层模拟实现
参考 SGI STL 里的 hash_set/hash_map(非标准,但结构清晰),它们复用同一个 hashtable。hash_set 存的是 key 本身,hash_map 存 pair<const K, V>。要想让 hashtable 能取出 key,就需要从上层传入一个仿函数。
下面我以自己的风格实现一份。命名空间用 zlr,整体思路类似:定义 KeyOfT 仿函数,set 直接返回 key,map 返回 pair 的 first。再把数据类型、哈希函数、KeyOfT 传给哈希表模板。
哈希表框架
哈希表用开放链地址法,节点里存数据 T 和 next 指针。扩容时用 STL 的素数序列,负载因子达到 1 就 rehash。
template<class K> struct HashFunc {
size_t operator()(const K& key) { return (size_t)key; }
};
template<> struct HashFunc<string> {
size_t operator()(const string& key) {
size_t hash = 0;
for (auto e : key) { hash *= 131; hash += e; }
return hash;
}
};
namespace hash_bucket {
template<class T> struct HashNode {
T _data;
HashNode<T>* _next;
HashNode(const T& data) :_data(data), _next(nullptr) {}
};
template<class K, class T, class KeyOfT, class Hash>
class HashTable {
typedef HashNode<T> Node;
inline unsigned long __stl_next_prime(unsigned long n) {
static const int __stl_num_primes = 28;
static const unsigned long __stl_prime_list[__stl_num_primes] = {
53, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593, 49157, 98317,
196613, 393241, 786433, 1572869, 3145739, 6291469, 12582917, 25165843,
50331653, 100663319, 201326611, 402653189, 805306457, 1610612741,
3221225473, 4294967291
};
const unsigned long* first = __stl_prime_list;
const unsigned long* last = __stl_prime_list + __stl_num_primes;
const unsigned long* pos = lower_bound(first, last, n);
return pos == last ? *(last - 1) : *pos;
}
public:
HashTable() { _tables.resize(__stl_next_prime(_tables.size()), nullptr); }
~HashTable() {
for (size_t i = 0; i < _tables.size(); i++) {
Node* cur = _tables[i];
while (cur) { Node* next = cur->_next; delete cur; cur = next; }
_tables[i] = nullptr;
}
}
bool Insert(const T& data) {
KeyOfT kot;
if (Find(kot(data))) return false;
Hash hs;
size_t hashi = hs(kot(data)) % _tables.size();
if (_n == _tables.size()) {
vector<Node*> newtables(__stl_next_prime(_tables.size()), nullptr);
for (size_t i = 0; i < _tables.size(); i++) {
Node* cur = _tables[i];
while (cur) {
Node* next = cur->_next;
size_t hashi = hs(kot(cur->_data)) % newtables.size();
cur->_next = newtables[hashi];
newtables[hashi] = cur;
cur = next;
}
_tables[i] = nullptr;
}
_tables.swap(newtables);
}
Node* newnode = new Node(data);
newnode->_next = _tables[hashi];
_tables[hashi] = newnode;
++_n;
return true;
}
private:
vector<Node*> _tables;
size_t _n = 0;
};
}
迭代器实现
哈希表迭代器是单向的,难点在 operator++:如果当前节点有后续节点就走过去,否则需要找到下一个非空桶。这要求迭代器持有哈希表的指针,所以得前置声明 HashTable。参考 SGI 的实现,__hashtable_iterator 里同时保存了节点指针和哈希表指针:
template <class Value, class Key, class HashFcn, class ExtractKey, class EqualKey, class Alloc>
struct __hashtable_iterator {
typedef hashtable<Value, Key, HashFcn, ExtractKey, EqualKey, Alloc> hashtable;
typedef __hashtable_iterator<Value, Key, HashFcn, ExtractKey, EqualKey, Alloc> iterator;
typedef __hashtable_const_iterator<Value, Key, HashFcn, ExtractKey, EqualKey, Alloc> const_iterator;
typedef __hashtable_node<Value> node;
typedef forward_iterator_tag iterator_category;
typedef Value value_type;
node* cur;
hashtable* ht;
__hashtable_iterator(node* n, hashtable* tab) : cur(n), ht(tab) {}
__hashtable_iterator() {}
reference operator*() const { return cur->val; }
pointer operator->() const { return &(operator*()); }
iterator& operator++();
iterator operator++(int);
bool operator==(const iterator& it) const { return cur == it.cur; }
bool operator!=(const iterator& it) const { return cur != it.cur; }
};
template <class V, class K, class HF, class ExK, class EqK, class A>
__hashtable_iterator<V, K, HF, ExK, EqK, A>& __hashtable_iterator<V, K, HF, ExK, EqK, A>::operator++() {
const node* old = cur;
cur = cur->next;
if (!cur) {
size_type bucket = ht->bkt_num(old->val);
while (!cur && ++bucket < ht->buckets.size()) cur = ht->buckets[bucket];
}
return *this;
}
template<class K, class T, class KeyOfT, class Hash> class HashTable;
template<class K, class T, class Ptr, class Ref, class KeyOfT, class Hash>
struct HTIterator {
typedef HashNode<T> Node;
typedef HTIterator<K, T, Ptr, Ref, KeyOfT, Hash> Self;
Node* _node;
const HashTable<K, T, KeyOfT, Hash>* _pht;
HTIterator(Node* node, const HashTable<K, T, KeyOfT, Hash>* pht) :_node(node), _pht(pht) {}
Ref operator*() { return _node->_data; }
Ptr operator->() { return &_node->_data; }
bool operator!=(const Self& s) { return _node != s._node; }
Self& operator++() {
if (_node->_next) {
_node = _node->_next;
} else {
KeyOfT kot;
Hash hs;
size_t hashi = hs(kot(_node->_data)) % _pht->_tables.size();
++hashi;
while (hashi < _pht->_tables.size()) {
if (_pht->_tables[hashi]) { break; }
++hashi;
}
if (hashi == _pht->_tables.size()) {
_node = nullptr;
} else {
_node = _pht->_tables[hashi];
}
}
return *this;
}
};
HashTable 里添加 Begin/End,并调整 Insert 返回值为 pair<Iterator, bool>:
template<class K, class T, class KeyOfT, class Hash>
class HashTable {
template<class K, class T, class Ptr, class Ref, class KeyOfT, class Hash>
friend struct HTIterator;
typedef HashNode<T> Node;
public:
typedef HTIterator<K, T, T*, T&, KeyOfT, Hash> Iterator;
typedef HTIterator<K, T, const T*, const T&, KeyOfT, Hash> ConstIterator;
Iterator Begin() {
if (_n == 0) return End();
for (size_t i = 0; i < _tables.size(); i++) {
Node* cur = _tables[i];
if (cur) { return Iterator(cur, this); }
}
return End();
}
Iterator End() { return Iterator(nullptr, this); }
ConstIterator Begin() const {
if (_n == 0) return End();
for (size_t i = 0; i < _tables.size(); i++) {
Node* cur = _tables[i];
if (cur) { return ConstIterator(cur, this); }
}
return End();
}
ConstIterator End() const { return ConstIterator(nullptr, this); }
pair<Iterator, bool> Insert(const T& data) {
KeyOfT kot;
Iterator it = Find(kot(data));
if (it != End()) return make_pair(it, false);
Hash hs;
size_t hashi = hs(kot(data)) % _tables.size();
if (_n == _tables.size()) {
vector<Node*> newtables(__stl_next_prime(_tables.size() + 1), nullptr);
for (size_t i = 0; i < _tables.size(); i++) {
Node* cur = _tables[i];
while (cur) {
Node* next = cur->_next;
size_t hashi = hs(kot(cur->_data)) % newtables.size();
cur->_next = newtables[hashi];
newtables[hashi] = cur;
cur = next;
}
_tables[i] = nullptr;
}
_tables.swap(newtables);
}
Node* newnode = new Node(data);
newnode->_next = _tables[hashi];
_tables[hashi] = newnode;
++_n;
return make_pair(Iterator(newnode, this), true);
}
Iterator Find(const K& key) {
KeyOfT kot;
Hash hs;
size_t hashi = hs(key) % _tables.size();
Node* cur = _tables[hashi];
while (cur) {
if (kot(cur->_data) == key) { return Iterator(cur, this); }
cur = cur->_next;
}
return End();
}
bool Erase(const K& key) {
KeyOfT kot;
Hash hs;
size_t hashi = hs(key) % _tables.size();
Node* prev = nullptr;
Node* cur = _tables[hashi];
while (cur) {
if (kot(cur->_data) == key) {
if (prev == nullptr) { _tables[hashi] = cur->_next; }
else { prev->_next = cur->_next; }
delete cur; --_n; return true;
}
prev = cur; cur = cur->_next;
}
return false;
}
private:
vector<Node*> _tables;
size_t _n = 0;
};
包装 unordered_set 和 unordered_map
有了带迭代器的哈希表,再包一层就简单了。unordered_set 将 key 类型设为 const K,防止修改;unordered_map 用 pair<const K, V> 禁止修改 key,但 value 可改。
namespace zlr {
template<class K, class Hash = HashFunc<K>>
class unordered_set {
struct SetKeyOfT {
const K& operator()(const K& key) { return key; }
};
public:
typedef typename hash_bucket::HashTable<K, const K, SetKeyOfT, Hash>::Iterator iterator;
typedef typename hash_bucket::HashTable<K, const K, SetKeyOfT, Hash>::ConstIterator const_iterator;
iterator begin() { return _ht.Begin(); }
iterator end() { return _ht.End(); }
const_iterator begin() const { return _ht.Begin(); }
const_iterator end() const { return _ht.End(); }
pair<iterator, bool> insert(const K& key) { return _ht.Insert(key); }
iterator Find(const K& key) { return _ht.Find(key); }
bool Erase(const K& key) { return _ht.Erase(key); }
private:
hash_bucket::HashTable<K, const K, SetKeyOfT, Hash> _ht;
};
}
namespace zlr {
template<class K, class V, class Hash = HashFunc<K>>
class unordered_map {
struct MapKeyOfT {
const K& operator()(const pair<K, V>& kv) { return kv.first; }
};
public:
typedef typename hash_bucket::HashTable<K, pair<const K, V>, MapKeyOfT, Hash>::Iterator iterator;
typedef typename hash_bucket::HashTable<K, pair<const K, V>, MapKeyOfT, Hash>::ConstIterator const_iterator;
iterator begin() { return _ht.Begin(); }
iterator end() { return _ht.End(); }
const_iterator begin() const { return _ht.Begin(); }
const_iterator end() const { return _ht.End(); }
pair<iterator, bool> insert(const pair<K, V>& kv) { return _ht.Insert(kv); }
V& operator[](const K& key) {
pair<iterator, bool> ret = _ht.Insert(make_pair(key, V()));
return ret.first->second;
}
iterator Find(const K& key) { return _ht.Find(key); }
bool Erase(const K& key) { return _ht.Erase(key); }
private:
hash_bucket::HashTable<K, pair<const K, V>, MapKeyOfT, Hash> _ht;
};
}
operator[] 的实现依赖 Insert 返回的迭代器,写起来很自然。
快速验证
void test_set() {
zlr::unordered_set<int> s;
int a[] = { 4, 2, 6, 1, 3, 5, 15, 7, 16, 14, 3,3,15 };
for (auto e : a) { s.insert(e); }
for (auto e : s) { cout << e << " "; }
cout << endl;
zlr::unordered_set<int>::iterator it = s.begin();
while (it != s.end()) {
cout << *it << " "; ++it;
}
cout << endl;
}
void test_map() {
zlr::unordered_map<string, string> dict;
dict.insert({ "sort", "排序" });
dict.insert({ "left", "左边" });
dict.insert({ "right", "右边" });
dict["left"] = "左边,剩余";
dict["insert"] = "插入";
dict["string"];
zlr::unordered_map<string, string>::iterator it = dict.begin();
while (it != dict.end()) {
it->second += 'x';
cout << it->first << ":" << it->second << endl;
++it;
}
cout << endl;
}
运行结果符合预期,迭代器遍历的顺序没什么规律,这就是 unordered 容器的特点。整个实现虽然比红黑树版本的 map/set 繁琐一些,但思路是清晰的:关键就是通过仿函数解耦 key 的提取,让同一个哈希表能同时服务 set 和 map。
相关免费在线工具
- Base64 字符串编码/解码
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
- Base64 文件转换器
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
- Markdown转HTML
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online
- HTML转Markdown
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online
- JSON 压缩
通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online
- JSON美化和格式化
将JSON字符串修饰为友好的可读格式。 在线工具,JSON美化和格式化在线工具,online