
🔥小叶-duck:个人主页
❄️个人专栏:《Data-Structure-Learning》《C++入门到进阶&自我学习过程记录》
《算法题讲解指南》--优选算法
《算法题讲解指南》--递归、搜索与回溯算法
《算法题讲解指南》--动态规划算法
✨未择之路,不须回头
已择之路,纵是荆棘遍野,亦作花海遨游
目录
[一. unordered_map/unordered_set源码及框架分析](#一. unordered_map/unordered_set源码及框架分析)
[2.1 哈希表模板参数设计](#2.1 哈希表模板参数设计)
[2.2 实现出复用哈希表的框架,并支持insert](#2.2 实现出复用哈希表的框架,并支持insert)
[2.3 实现迭代器:支持哈希桶遍历](#2.3 实现迭代器:支持哈希桶遍历)
[2.4 map支持[]](#2.4 map支持[])
[测试代码(test .cpp):](#测试代码(test .cpp):)
前言
STL 中的 unordered_map 和 unordered_set 以高效的增删查性能(平均 O (1) 时间复杂度)成为高频使用的关联式容器,其底层核心 是哈希表(哈希桶) 。但很多朋友只知道如何使用这两个容器,却不清楚究竟是怎么实现的 ------ 如何基于哈希表封装出支持 key-value 存储和 key-only 存储的两种容器?使用迭代器iterator在++的时候是如何找到下一个位置?如何保证 key 的唯一性?
在前面的文章中我们已经对哈希表的实现进行了详细的讲解,其中已经讲解了哈希冲突如何解决、哈希函数如何实现等,也是为本篇文章封装两个容器做铺垫。本文结合核心思路,从哈希表的泛型设计入手,一步步拆解 myunordered_map 和 myunordered_set 的封装逻辑,包括哈希函数适配、迭代器实现、key 约束等关键细节,附完整实现代码,帮你吃透哈希表在容器封装中的实战应用。
一. unordered_map/unordered_set源码及框架分析
SGI-STL30版本源代码中没有unordered_map和unordered_set,SGI-STL30版本是C++11之前的STL版本,这两个容器是C++11之后才更新的。但是SGI-STL30实现了哈希表,容器的名字是hash_map和hash_set,他是作为非标准的容器出现的,非标准是指非C++标准规定必须实现的,源代码在hash_map/hash_set/stl_hash_map/stl_hash_set/stl_hashtable.h中:
hash_map和hash_set的实现结构框架核心部分截取出来如下:
stl_hash_set:
cpp
// stl_hash_set
template <class Value, class HashFcn = hash<Value>,
class EqualKey = equal_to<Value>,
class Alloc = alloc>
class hash_set
{
private:
typedef hashtable<Value, Value, HashFcn, identity<Value>,
EqualKey, Alloc> ht;
ht rep;
public:
typedef typename ht::key_type key_type;
typedef typename ht::value_type value_type;
typedef typename ht::hasher hasher;
typedef typename ht::key_equal key_equal;
typedef typename ht::const_iterator iterator;
typedef typename ht::const_iterator const_iterator;
hasher hash_funct() const { return rep.hash_funct(); }
key_equal key_eq() const { return rep.key_eq(); }
};
stl_hash_map:
cpp
// stl_hash_map
template <class Key, class T, class HashFcn = hash<Key>,
class EqualKey = equal_to<Key>,
class Alloc = alloc>
class hash_map
{
private:
typedef hashtable<pair<const Key, T>, Key, HashFcn,
select1st<pair<const Key, T> >, EqualKey, Alloc> ht;
ht rep;
public:
typedef typename ht::key_type key_type;
typedef T data_type;
typedef T mapped_type;
typedef typename ht::value_type value_type;
typedef typename ht::hasher hasher;
typedef typename ht::key_equal key_equal;
typedef typename ht::iterator iterator;
typedef typename ht::const_iterator const_iterator;
};
stl_hashtable.h:
cpp
// stl_hashtable.h
template <class Value, class Key, class HashFcn,
class ExtractKey, class EqualKey,
class Alloc>
class hashtable {
public:
typedef Key key_type;
typedef Value value_type;
typedef HashFcn hasher;
typedef EqualKey key_equal;
private:
hasher hash;
key_equal equals;
ExtractKey get_key;
typedef __hashtable_node<Value> node;
vector<node*, Alloc> buckets;
size_type num_elements;
public:
typedef __hashtable_iterator<Value, Key, HashFcn, ExtractKey, EqualKey,
Alloc> iterator;
pair<iterator, bool> insert_unique(const value_type& obj);
const_iterator find(const key_type& key) const;
};
template <class Value>
struct __hashtable_node
{
__hashtable_node* next;
Value val;
};
- 这里我们就不再画图分析了,通过源码可以看到,结构上 hash_map 和 hash_set 跟 map 和 set 的完全类似,复用同一个 hashtable 实现 key 和 key/value 结构,hash_set 传给hash_table 的是两个 key,hash_map 传给 hash_table 的是一个 key 和 一个 pair<const key,value>(第一个key的作用和set/map的红黑树封装一样,调用find/erase函数需要传key值)
- 需要注意的是源码里面跟map/set源码类似,命名风格比较乱,这里比map和set还乱,hash_set模板参数居然用的Value命名,hash_map用的是Key和T命名。
二、核心设计思路:哈希表的泛型复用
myunordered_map 和 myunordered_set 复用同一哈希表底层,核心通过模板参数抽象 和仿函数提取 key,实现 "一颗哈希表适配两种存储场景":
- myunordered_set:存储单个 key(去重 + 无序),需提取 key 本身进行哈希和比较;
- myunordered_map:存储 key-value 对(key 去重 + 无序),需提取 pair 中的 first 作为 key 进行哈希和比较。
2.1 哈希表模板参数设计
哈希表需支持三种核心抽象,通过模板参数暴露接口,适配不同容器需求:
cpp
template<class K, class T, class KeyofT, class Hash>
class HashTable
{
// K:哈希和查找时的key类型(myunordered_set为K,myunordered_map为K)
// T:哈希表节点存储的实际数据类型(myunordered_set为K,myunordered_map为pair<const K, V>)
// Hash:哈希函数仿函数(将K转为整形用于计算桶位置)
// KeyOfT:从T中提取K的仿函数(适配T的不同类型:如pair)
};
2.2 实现出复用哈希表的框架,并支持insert
- 参考源码框架,unordered_set 和 unordered_map 复用之前我们实现的哈希表。
- 我们这里相比源码调整一下,key参数就用K,value参数就用V,哈希表中结点存储的实际数据类型,我们使用T
- 其次跟map和set相比而言unordered_map和unordered_set的模拟实现类结构更复杂一点,但是大框架和思路是完全类似的。因为HashTable实现了泛型不知道T参数导致是K,还是pair<K,V>,那么insert 内部进行插入时要用K对象转换成整形取模和K比较相等,因为pair的value不参与计算取模,且默认支持的是key和value一起比较相等,我们需要时的任何时候只需要比较K对象 ,所以我们在unordered_map和unordered_set层分别实现一个MapKeyofT和SetKeyofT的仿函数传给HashTable的KeyofT ,然后HashTable中通过KeyofT仿函数取出T类型对象中的K对象 ,再转换成整形取模和K比较相等。
具体细节参考如下部分代码实现来进行理解:
cpp
// MyUnorderedSet.h
namespace xiaoye
{
template<class K, class Hash = HashFunc<K>>
struct unordered_set
{
struct KeyofSet
{
const K& operator()(const K& key)
{
return key;
}
};
public:
bool insert(const K& key)
{
return _ht.Insert(key);
}
private:
HashTable<K, const K, KeyofSet, Hash> _ht;
};
}
cpp
// MyUnorderedMap.h
namespace xiaoye
{
template<class K, class V, class Hash = HashFunc<K>>
struct unordered_map
{
// 仿函数:从T(pair<const K, V>)中提取key
struct KeyofMap
{
const K& operator()(const pair<K, V>& kv)
{
return kv.first;
}
};
public:
bool insert(const pair<K, V>& kv)
{
return _ht.Insert(kv);
}
private:
HashTable<K, pair<const K, V>, KeyofMap, Hash> _ht;
};
}
这里讲一下为什么unordered_map和unordered_set的成员变量 _ht 类型 HashTable 中第二个参数都用 const 进行修饰?
首先 HashTable 类模板的第二个模板参数为 T,说明我们是将哈希表节点存储的实际数据中的key值进行const修饰(也就是不允许修改key),因为哈希表存放数据就是依赖数据中key值在哈希表中桶位置的映射关系,一旦修改了key值,则映射关系就会出现问题。
Insert实现:
cpp
// HashTable.h
// 质数表(SGI STL 同款,用于扩容)
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
};
inline unsigned long __stl_next_prime(unsigned long n)
{
const unsigned long* first = __stl_prime_list;
const unsigned long* last = __stl_prime_list + __stl_num_primes;
// >= n
const unsigned long* pos = lower_bound(first, last, n);
return pos == last ? *(last - 1) : *pos;
}
// 哈希函数仿函数
template<class K>
struct HashFunc
{
size_t operator()(const K& key)
{
return size_t(key); // 默认可支持直接转换
}
};
// 特化string类型的哈希函数
template<>
struct HashFunc<string>
{
// BKDR字符串哈希算法
size_t operator()(const string& key)
{
size_t hash = 0;
for (auto ch : key)
{
// 字符串转换成整形,可以把字符ascii码相加即可
hash += ch;// 累加字符ASCII码
hash *= 131;// 乘质数131,减少冲突
}
return hash;
}
};
// 哈希桶节点结构(链表节点)
template<class T>
struct HashNode
{
T _data;
HashNode* _next;
HashNode(const T& data)
:_data(data)
, _next(nullptr)
{ }
};
template<class K, class T, class KeyofT, class Hash>
class HashTable
{
public:
typedef HashNode<T> Node;
//构造函数
HashTable()
:_tables(__stl_next_prime(0))
, _n(0)
{ }
//析构函数
~HashTable()
{
for (size_t i = 0; i < _tables.size(); i++)
{
Node* cur = _tables[i];
while (cur)
{
Node* next = cur->_next;
_tables[i] = next;
delete cur;
cur = next;
}
}
_n = 0;
}
// 插入key-value对(头插法,去重需先查找)
bool Insert(const T& data)
{
KeyofT kot;
if (Find(kot(data)))
{
return false;
}
Hash hs;
if (_n == _tables.size())
{
//迁移旧表节点到新表(直接移动节点,不新建,效率更高)
vector<Node*> newtables(__stl_next_prime(_tables.size() + 1));
for (int i = 0; i < _tables.size(); i++)
{
// 遍历旧表,旧表节点重新映射,挪动到新表
Node* cur = _tables[i];
while (cur)
{
//重新计算节点在新表的位置
size_t hashi = hs(kot(cur->_data)) % newtables.size();
//头插入新表
Node* next = cur->_next;
cur->_next = newtables[hashi];
newtables[hashi] = cur;
cur = next;
}//while循环结束说明第i位置的链表结点已经全部挪走了,需要置空
_tables[i] = nullptr;
}
_tables.swap(newtables);
}
//头插入当前节点
size_t hashi = hs(kot(data)) % _tables.size();
Node* newnode = new Node(data);
newnode->_next = _tables[hashi];//newnode的下一个位置指向hashi位置的头节点
_tables[hashi] = newnode; //让newnode变为头节点
_n++;
return true;
}
private:
vector<Node*> _tables;// 指针数组(存储每个链表头指针)
size_t _n = 0;
};
2.3 实现迭代器:支持哈希桶遍历
iterator实现思路分析:
- iterator 实现的大框架跟 list 的 iterator 思路是⼀致的(因为哈希桶本质就是将结点通过指针像衣架挂起来),用⼀个类型封装结点的指针 ,再通过重载运算符实现,迭代器像指针⼀样访问的行为 ,要注意的是哈希表的迭代器是单向迭代器。
- 这里的难点是 operator++ 的实现。iterator 中有⼀个指向结点的指针,如果当前桶下面还有结点 ,则结点的指针指向下⼀个结点 即可。如果当前桶走完了 ,则需要想办法计算找到下⼀个桶 。这里的难点是反而是结构设计 的问题,参考上面的源码,我们可以看到 iterator 中除了有结点的指针,还有哈希表对象的指针 ,这样当前桶走完了,要计算下一个桶就相对容易多了,⽤ key 值计算出当前桶位置(这时候就需要利用哈希表对象的指针来获取桶的总个数),依次往后找下⼀个不为空的桶即可。
- begin()返回第一个不为空的桶中第⼀个节点指针构造的迭代器,这⾥end()返回迭代器可以用空表示。
- unordered_set 的 iterator 不支持修改,这也是为什么我们把 unordered_set 的第二个模板参数改成 const K 的原因之一:HashTable<K, const K, SetKeyofT, Hash> _ht;
- unordered_map 的 iterator 不支持修改 key 但是可以修改 value,这也是为什么我们把unordered_map 的第⼆个模板参数 pair 的第⼀个参数改成 const K:HashTable<K, pair<const K, V>,MapKeyofT, Hash> _ht;
cpp
//哈希表迭代器
template<class K, class T, class Res, class Ptr, class KeyofT, class Hash>
struct HashTableIterator
{
typedef HashTableIterator<K, T, Res, Ptr, KeyofT, Hash> Self;
typedef HashNode<T> Node;
typedef HashTable<K, T, KeyofT, Hash> HT;
Node* _cur;// 当前指向的节点
const HT* _ht;// 指向哈希表,通过获取桶的总个数来计算当前结点所在桶的位置,以此进行桶切换
//由于const迭代器实现原因,ConstIterator Begin() const 会修饰返回的this指针
//导致this指针指向对象的内容被const修饰,但是传过来构造时如果是普通对象则权限放大了
//所以_ht需要加上const修饰
// 迭代器构造函数
HashTableIterator(Node* cur, const HT* ht)
:_cur(cur)
,_ht(ht)
{ }
// 解引用运算符(返回节点数据引用)
Res operator*()
{
return _cur->_data;
}
// 箭头运算符(支持->访问成员,如map的first/second)
Ptr operator->()
{
return &_cur->_data;
}
bool operator!=(const Self& s) const
{
return _cur != s._cur;
}
// 前置++(核心:遍历当前桶所有节点后,切换到下一个非空桶)
Self& operator++()
{
if (_cur->_next)
{
//当前桶还有数据,走到当前桶的下一个结点
_cur = _cur->_next;
}
else
{
//当前桶已经走完了,需要找到下一个不为空的桶
KeyofT kot;
Hash ht;
size_t hashi = ht(kot(_cur->_data)) % _ht->_tables.size();
hashi++;//先走到下一个桶,进行判断是否为空
while (hashi < _ht->_tables.size())
{
_cur = _ht->_tables[hashi];
if (_cur)
{
//当前走到的桶不为空,cur就是当前桶的头节点位置,直接返回
break;
}
hashi++;
}
//这里的特殊处理情况为:当_cur为最后一个桶的最后一个结点
//则上面的while循环会直接结束,但_cur仍然有值,需要特殊处理为空
if (hashi == _ht->_tables.size())
{
_cur = nullptr;
}
}
return *this;
}
};
2.4 map支持[]
unordered_map 要支持[]主要需要修改insert返回值支持,修改 HashTable 中的 insert 返回值为:
cpp
pair<Iterator,bool> Insert(const T& data);
有了insert,支持[ ]实现就很简单了,具体 insert 修改代码和 [ ] 实现会在最后全部进行展示。
三、完整代码实现(附详细注释)
HashTable.h:
cpp
#include<iostream>
#include<vector>
#include<string>
using namespace std;
// 质数表(SGI STL 同款,用于扩容)
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
};
inline unsigned long __stl_next_prime(unsigned long n)
{
const unsigned long* first = __stl_prime_list;
const unsigned long* last = __stl_prime_list + __stl_num_primes;
// >= n
const unsigned long* pos = lower_bound(first, last, n);
return pos == last ? *(last - 1) : *pos;
}
// 哈希函数仿函数
template<class K>
struct HashFunc
{
size_t operator()(const K& key)
{
return size_t(key); // 默认可支持直接转换
}
};
// 特化string类型的哈希函数
template<>
struct HashFunc<string>
{
// BKDR字符串哈希算法
size_t operator()(const string& key)
{
size_t hash = 0;
for (auto ch : key)
{
// 字符串转换成整形,可以把字符ascii码相加即可
hash += ch;// 累加字符ASCII码
hash *= 131;// 乘质数131,减少冲突
}
return hash;
}
};
// 哈希桶节点结构(链表节点)
template<class T>
struct HashNode
{
T _data;
HashNode* _next;
HashNode(const T& data)
:_data(data)
, _next(nullptr)
{ }
};
//前置声明HashTable类模板,因为HashTableIterator中operator++需要哈希桶的长度,如果不加则编译器找不到
template<class K, class T, class KeyofT, class Hash>
class HashTable;
//哈希表迭代器
template<class K, class T, class Res, class Ptr, class KeyofT, class Hash>
struct HashTableIterator
{
typedef HashTableIterator<K, T, Res, Ptr, KeyofT, Hash> Self;
typedef HashNode<T> Node;
typedef HashTable<K, T, KeyofT, Hash> HT;
Node* _cur;// 当前指向的节点
const HT* _ht;// 指向哈希表,通过获取桶的总个数来计算当前结点所在桶的位置,以此进行桶切换
//由于const迭代器实现原因,ConstIterator Begin() const 会修饰返回的this指针
//导致this指针指向对象的内容被const修饰,但是传过来构造时如果是普通对象则权限放大了
//所以_ht需要加上const修饰
// 迭代器构造函数
HashTableIterator(Node* cur, const HT* ht)
:_cur(cur)
,_ht(ht)
{ }
// 解引用运算符(返回节点数据引用)
Res operator*()
{
return _cur->_data;
}
// 箭头运算符(支持->访问成员,如map的first/second)
Ptr operator->()
{
return &_cur->_data;
}
bool operator!=(const Self& s) const
{
return _cur != s._cur;
}
// 前置++(核心:遍历当前桶所有节点后,切换到下一个非空桶)
Self& operator++()
{
if (_cur->_next)
{
//当前桶还有数据,走到当前桶的下一个结点
_cur = _cur->_next;
}
else
{
//当前桶已经走完了,需要找到下一个不为空的桶
KeyofT kot;
Hash ht;
size_t hashi = ht(kot(_cur->_data)) % _ht->_tables.size();
hashi++;//先走到下一个桶,进行判断是否为空
while (hashi < _ht->_tables.size())
{
_cur = _ht->_tables[hashi];
if (_cur)
{
//当前走到的桶不为空,cur就是当前桶的头节点位置,直接返回
break;
}
hashi++;
}
//这里的特殊处理情况为:当_cur为最后一个桶的最后一个结点
//则上面的while循环会直接结束,但_cur仍然有值,需要特殊处理为空
if (hashi == _ht->_tables.size())
{
_cur = nullptr;
}
}
return *this;
}
};
template<class K, class T, class KeyofT, class Hash>
// K:哈希、查找和删除时的key类型(myunordered_set为K,myunordered_map为K)
// T:哈希表节点存储的实际数据类型(myunordered_set为K,myunordered_map为pair<const K, V>)
// Hash:哈希函数仿函数(将K转为整形用于计算桶位置)
// KeyOfT:从T中提取K的仿函数(适配T的不同类型:如pair)
class HashTable
{
//友元声明类模板HashTableIterator,为了_ht能使用私有成员_tables
//友元声明和前置声明类模板都需要将模板参数带上
template<class K, class T, class Res, class Ptr, class KeyofT, class Hash>
friend struct HashTableIterator;
public:
typedef HashNode<T> Node;
typedef HashTableIterator<K, T, T&, T*, KeyofT, Hash> Iterator;
typedef HashTableIterator<K, T, const T&, const T*, KeyofT, Hash> ConstIterator;
Iterator Begin()
{
for (size_t i = 0; i < _tables.size(); i++)
{
if (_tables[i])
{
return Iterator(_tables[i], this);
}
}
return End();
}
Iterator End()
{
return Iterator(nullptr, this);
}
ConstIterator Begin() const
{
for (size_t i = 0; i < _tables.size(); i++)
{
if (_tables[i])
{
return ConstIterator(_tables[i], this);
//由于Begin()被const修饰,所以this指针指向对象的内容也不能进行修改
//此时this的类型完整表示为:const HashTable* const this
//所以如果上面迭代器构造中_ht(对应这里的this指针)不被const修饰,则调用const迭代器时就会出现权限放大报错
}
}
return End();
}
ConstIterator End() const
{
return ConstIterator(nullptr, this);
}
//构造函数
HashTable()
:_tables(__stl_next_prime(0))
, _n(0)
{ }
//析构函数
~HashTable()
{
for (size_t i = 0; i < _tables.size(); i++)
{
Node* cur = _tables[i];
while (cur)
{
Node* next = cur->_next;
_tables[i] = next;
delete cur;
cur = next;
}
}
_n = 0;
}
//拷贝构造(深拷贝)
HashTable(const HashTable<K, T, KeyofT, Hash>& ht)
{
this->_tables.resize(ht._tables.size());
for (size_t i = 0; i < ht._tables.size(); i++)
{
Node* cur = ht._tables[i];
while (cur)
{
Insert(cur->_kv);
cur = cur->_next;
}
}
}
void Swap(HashTable<K, T, KeyofT, Hash>& ht)
{
std::swap(_tables, ht._tables);
std::swap(_n, ht._n);
}
//赋值重载operator=(现代写法)
HashTable<K, T, KeyofT, Hash>& operator=(HashTable<K, T, KeyofT, Hash> ht)
{
if (this != &ht)
{
Swap(ht);
}
return *this;
}
// 插入key-value对(头插法,去重需先查找)
//bool Insert(const T& data)
pair<Iterator, bool> Insert(const T& data)
{
KeyofT kot;
auto it = Find(kot(data));
if (it != End())
{
return { it, true };
}
Hash hs;
if (_n == _tables.size())
{
//迁移旧表节点到新表(直接移动节点,不新建,效率更高)
vector<Node*> newtables(__stl_next_prime(_tables.size() + 1));
for (int i = 0; i < _tables.size(); i++)
{
// 遍历旧表,旧表节点重新映射,挪动到新表
Node* cur = _tables[i];
while (cur)
{
//重新计算节点在新表的位置
size_t hashi = hs(kot(cur->_data)) % newtables.size();
//头插入新表
Node* next = cur->_next;
cur->_next = newtables[hashi];
newtables[hashi] = cur;
cur = next;
}//while循环结束说明第i位置的链表结点已经全部挪走了,需要置空
_tables[i] = nullptr;
}
_tables.swap(newtables);
}
//头插入当前节点
size_t hashi = hs(kot(data)) % _tables.size();
Node* newnode = new Node(data);
newnode->_next = _tables[hashi];//newnode的下一个位置指向hashi位置的头节点
_tables[hashi] = newnode; //让newnode变为头节点
_n++;
return { Iterator(newnode, this), true };
}
//Node* Find(const K& key)
Iterator Find(const K& key)
{
Hash hs;
KeyofT kot;
size_t hashi = hs(key) % _tables.size();
Node* cur = _tables[hashi];
while (cur)
{
if (kot(cur->_data) == key)
{
return { cur, this };
}
cur = cur->_next;
}
return { nullptr, this };
}
// 删除key(链表节点删除)
bool Erase(const K& key)
{
Hash hs;
size_t hashi = hs(key) % _tables.size();
Node* cur = _tables[hashi];
Node* prev = nullptr; //提前获取链表当前结点的上一个结点
//用于判断删除的是头节点还是中间结点
while (cur)
{
if (kot(cur->_data) == key)
{
if (prev == nullptr)
{
//prev为空说明删除链表头节点
_tables[hashi] = cur->_next;
}
else
{
//prev不为空说明删除中间结点
prev->_next = cur->_next;
}
delete cur;
_n--;
return true;
}
else
{
prev = cur;
cur = cur->_next;
}
}
return false;
}
private:
vector<Node*> _tables;// 指针数组(存储每个链表头指针)
size_t _n = 0;
};
unordered_set.h:
cpp
#include "HashTable.h"
namespace xiaoye
{
template<class K, class Hash = HashFunc<K>>
struct unordered_set
{
struct KeyofSet
{
const K& operator()(const K& key)
{
return key;
}
};
public:
typedef typename HashTable<K, const K, KeyofSet, Hash>::Iterator iterator;
typedef typename HashTable<K, const K, KeyofSet, 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);
}
void print()
{
return _print(*this);
}
iterator find(const K& key)
{
return _ht.Find(key);
}
bool erase(const K& key)
{
return _ht.Erase(key);
}
private:
void _print(const unordered_set<K, Hash>& s)
{
unordered_set<K, Hash>::const_iterator it = s.begin();
while (it != s.end())
{
cout << *it << " ";
++it;
}
cout << endl;
}
HashTable<K, const K, KeyofSet, Hash> _ht;
};
}
unordered_map.h:
cpp
#include "HashTable.h"
namespace xiaoye
{
template<class K, class V, class Hash = HashFunc<K>>
struct unordered_map
{
// 仿函数:从T(pair<const K, V>)中提取key
struct KeyofMap
{
const K& operator()(const pair<K, V>& kv)
{
return kv.first;
}
};
public:
typedef typename HashTable<K, pair<const K, V>, KeyofMap, Hash>::Iterator iterator;
typedef typename HashTable<K, pair<const K, V>, KeyofMap, 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);
}
void print()
{
return _print(*this);
}
iterator find(const K& key)
{
return _ht.Find(key);
}
bool erase(const K& key)
{
return _ht.Erase(key);
}
V& operator[](const K& key)
{
pair<iterator, bool> ret = _ht.Insert({ key, V() });
return ret.first->second;
}
private:
void _print(const unordered_map<K, V, Hash>& s)
{
unordered_map<K, V, Hash>::const_iterator it = s.begin();
while (it != s.end())
{
cout << it->first << ":" << it->second << endl;
++it;
}
cout << endl;
}
HashTable<K, pair<const K, V>, KeyofMap, Hash> _ht;
};
}
测试代码(test .cpp):
cpp
#include"UnorderedSet.h"
#include"UnorderedMap.h"
void test_unorderedset1()
{
int arr1[] = { 63, 51, 16, 27, 68, 52, 1, 1, 45, 6, 17, 6 };
xiaoye::unordered_set<int> s1;
for (auto e : arr1)
{
s1.insert(e);
}
xiaoye::unordered_set<int>::iterator it = s1.begin();
while (it != s1.end())
{
cout << *it << " ";
++it;
}
cout << endl;
s1.print();
}
void test_unorderedmap1()
{
xiaoye::unordered_map<string, string> dict;
dict.insert({ "sort", "排序" });
dict.insert({ "left", "左边" });
dict.insert({ "right", "右边" });
/*for (auto e : dict)
{
cout << e.first << ":" << e.second << endl;
}
cout << endl;*/
xiaoye::unordered_map<string, string>::iterator it = dict.begin();
while (it != dict.end())
{
//unordered_map允许修改second(value),但不允许修改first(key)
//it->first += 'x';
cout << it->first << ":" << it->second << endl;
it->second += 'x';
++it;
}
cout << endl;
dict.print();
dict["left"] = "左边、剩余";
dict["insert"] = "插入";
dict["string"];
dict.print();
}
int main()
{
cout << "测试unorderedset:" << endl;
test_unorderedset1();
cout << endl;
cout << "测试unorderedmap:" << endl;
test_unorderedmap1();
cout << endl;
return 0;
}

结束语
到此,利用哈希表封装 myunordered_map/myunordered_set的实现就全部讲解完了。myunordered_map 和 myunordered_set 的封装核心是 "哈希表泛型复用 + 仿函数解耦"------ 通过模板参数抽象不同容器的存储需求,用仿函数屏蔽 key 提取、哈希计算、相等比较的差异,最终实现 "一套底层哈希表,支撑两种容器功能"。掌握这套封装逻辑,不仅能理解 STL unordered 系列容器的底层实现,更能学会 "泛型编程 + 接口抽象" 的设计思想,在实际开发中灵活适配不同存储场景。希望对大家学习C++能有所收获!
C++参考文档:
https://legacy.cplusplus.com/reference/
https://zh.cppreference.com/w/cpp
https://en.cppreference.com/w/