C++学习笔记——哈希表

哈希表

1. 概念

哈希(hash)又称散列,是一种组织数据的方式。从译名来看,有散乱排列的意思。本质就是通过哈希函数把关键字Key跟存储位置建立一个映射关系,查找时通过这个哈希函数计算出Key存储的位置,进行快速查找。(哈希和哈希表并不是一个概念,前者更偏向一种思想)

1.1 直接定址法

当关键字的范围比较集中时,直接定址法就是非常简单高效的方法,比如一组关键字都在[0,99]之间,那么我们开一个100个数的数组,每个关键字的值直接就是存储位置的下标。再比如一组关键字值都在[a,z]的小写字母,那么我们开一个26个数的数组,每个关键字ch - 'a'就是存储位置的下标。也就是说直接定址法本质就是用关键字计算出一个绝对位置或者相对位置。

字符串中的第一个唯一字符 - LeetCode

1.2 哈希冲突

直接定址法的缺点也非常明显,当关键字的范围比较分散时,就很浪费内存甚至内存不够用。假设我们只有数据范围是[0, 9999]的N个值,我们要映射到一个M个空间的数组中(一般情况下M >= N),那么就要借助哈希函数(hash function)hf,关键字key被放到数组的h(key)位置,这里要注意的是h(key)计算出的值必须在[0, M)之间。

这里存在的一个问题就是,两个不同的key可能会映射到同一个位置去,这种问题我们叫做哈希冲突,或者哈希碰撞。理想情况是找出一个好的哈希函数避免冲突,但是实际场景中,冲突是不可避免的,所以我们尽可能设计出优秀的哈希函数,减少冲突的次数,同时也要去设计出解决冲突的方案。

1.3 负载因子

假设哈希表中已经映射存储了N个值,哈希表的大小为M,那么 负载因子 = N / M 负载因子=N/M 负载因子=N/M,负载因子有些地方也翻译为载荷因子/装载因子等,他的英文为load factor。负载因子越大,哈希冲突的概率越高,空间利用率越高;负载因子越小,哈希冲突的概率越低,空间利用率越低;

1.4 哈希函数

一个好的哈希函数应该让N个关键字被等概率的均匀的散列分布到哈希表的M个空间中,但是实际中却很难做到,但是我们要尽量往这个方向去考量设计。

1.4.1 除法散列法/除留余数法
  • 除法散列法也叫做除留余数法,顾名思义,假设哈希表的大小为M,那么通过key除以M的余数作为映射位置的下标,也就是哈希函数为:h(key) = key % M。
  • 当使用除法散列法时,要尽量避免M为某些值,如2的幂,10的幂等。如果是 2 X 2^X 2X,那么key % 2 X 2^X 2X本质相当于保留key的后X位,那么后x位相同的值,计算出的哈希值都是一样的,就冲突了。
  • 当使用除法散列法时,建议M取不太接近2的整数次幂的一个质数(素数)。
  • 需要说明的是,实践中也是八仙过海,各显神通,Java的HashMap采用除法散列法时就是2的整数次幂做哈希表的大小M,这样玩的话,就不用取模,而可以直接位运算,相对而言位运算比模更高效一些。但是他不是单纯的去取模,比如M是2^16次方,本质是取后16位,那么用key' =key>>16,然后把key和key' 异或的结果作为哈希值。也就是说我们映射出的值还是在[0,M)范围内,但是尽量让key所有的位都参与计算,这样映射出的哈希值更均匀一些即可。
1.4.2 乘法散列法(了解)
  • 乘法散列法对哈希表大小M没有要求,他的大思路第一步:用关键字 K 乘上常数 A (0<A<1),并抽取出 k*A 的小数部分。第二步:后再用M乘以k*A 的小数部分,再向下取整。
  • h ( k e y ) = f l o o r ( M × ( ( A × k e y ) % 1.0 ) ) h(key)=floor(M×((A×key)\%1.0)) h(key)=floor(M×((A×key)%1.0)),其中floor表示对表达式进行下取整,A∈(0,1),这里最重要的是A的值应该如何设定,Knuth认为 A = ( 5 − 1 ) / 2 = 0.6180339887.... A=(\sqrt5-1)/2=0.6180339887.... A=(5 −1)/2=0.6180339887....(黄金分割点)比较好。
  • 乘法散列法对哈希表大小M是没有要求的,假设M为1024,key为1234,A = 0.6180339887, A*key= 762.6539420558,取小数部分为0.6539420558, M×((A×key)%1.0) = 0.6539420558*1024 =669.6366651392,那么h(1234) = 669。
1.4.3 全域散列法(了解)
  • 如果存在一个恶意的对手,他针对我们提供的散列函数,特意构造出一个发生严重冲突的数据集,比如,让所有关键字全部落入同一个位置中。这种情况是可以存在的,只要散列函数是公开且确定的,就可以实现此攻击。解决方法自然是见招拆招,给散列函数增加随机性,攻击者就无法找出确定可以导致最坏情况的数据。这种方法叫做全域散列。
  • h a b ( k e y ) = ( ( a × k e y + b ) % P ) % M h_{ab}(key)=((a×key+b)\%P)\%M hab(key)=((a×key+b)%P)%M,P需要选一个足够大的质数,a可以随机选[1,P-1]之间的任意整数,b可以随机选[0,P-1]之间的任意整数,这些函数构成了一个P*(P-1)组全域散列函数组。假设P=17,M=6,a = 3, b = 4, 则 h 34 ( 8 ) = ( ( 3 × 8 + 4 ) % 17 ) % 6 = 5 h_{34}(8)=((3×8+4)\%17)\%6=5 h34(8)=((3×8+4)%17)%6=5。
  • 需要注意的是每次初始化哈希表时,随机选取全域散列函数组中的一个散列函数使用,后续增删查改都固定使用这个散列函数,否则每次哈希都是随机选一个散列函数,那么插入是一个散列函数,查找又是另一个散列函数,就会导致找不到插入的key了。

1.5 处理哈希冲突

实践中哈希表一般还是选择除法散列法作为哈希函数,当然哈希表无论选择什么哈希函数也避免不了冲突,那么插入数据时,如何解决冲突呢?主要有两种两种方法,开放定址法和链地址法。

1.5.1 开放定址法

在开放定址法中所有的元素都放到哈希表里,当一个关键字key用哈希函数计算出的位置冲突了,则按照某种规则找到一个没有存储数据的位置进行存储,开放定址法中负载因子一定是小于的。这里的规则有三种:线性探测、二次探测、双重探测。

线性探测

  • 从发生冲突的位置开始,依次线性向后探测,直到寻找到下一个没有存储数据的位置为止,如果走到哈希表尾,则回绕到哈希表头的位置。
  • h ( k e y ) = h a s h 0 = k e y % M h(key)=hash0=key\%M h(key)=hash0=key%M,hash0位置冲突了,则线性探测公式为: h c ( k e y , i ) = h a s h i = ( h a s h 0 + i ) % M , i = 1 , 2 , 3 , . . . , M − 1 hc(key,i)=hashi=(hash0+i)\%M,i={1,2,3,...,M-1} hc(key,i)=hashi=(hash0+i)%M,i=1,2,3,...,M−1,因为负载因子小于1,则最多探测M-1次,一定能找到一个存储key的位置。
  • 线性探测的比较简单且容易实现,线性探测的问题假设,hash0位置连续冲突,hash0,hash1,hash2位置已经存储数据了,后续映射到hash0,hash1,hash2,hash3的值都会争夺hash3位置,这种现象叫做群集/堆积。下面的二次探测可以一定程度改善这个问题。

二次探测

  • 从发生冲突的位置开始,依次左右按二次方跳跃式探测,直到寻找到下一个没有存储数据的位置为止,如果往右走到哈希表尾,则回绕到哈希表头的位置;如果往左走到哈希表头,则回绕到哈希表尾的位置;
  • h ( k e y ) = h a s h 0 = k e y % M h(key)=hash0=key\%M h(key)=hash0=key%M,hash0位置冲突了,则二次探测公式为: h c ( k e y , i ) = h a s h i = ( h a s h 0 ± i 2 ) % M , i = 1 , 2 , 3 , . . , M / 2 hc(key,i)=hashi=(hash0 ±i^2)\%M,i={1,2,3,..,M/2} hc(key,i)=hashi=(hash0±i2)%M,i=1,2,3,..,M/2
  • 二次探测当 h a s h i = ( h a s h 0 − i 2 ) % M hashi=(hash0-i^2)\%M hashi=(hash0−i2)%M时,当hashi<0时,需要hashi += M

双重散列(了解)

  • 第一个哈希函数计算出的值发生冲突,使用第二个哈希函数计算出一个跟key相关的偏移量值,不断往后探测,直到寻找到下一个没有存储数据的位置为止。
  • h 1 ( k e y ) = h a s h 0 = k e y % M h_1(key)=hash0=key\%M h1(key)=hash0=key%M,hash0位置冲突了,则双重探测公式为: h c ( k e y , i ) = h a s h i = ( h a s h 0 + i ∗ h 2 ( k e y ) ) % M , i = 1 , 2 , 3 , . . . , M hc(key,i)=hashi=(hash0+i*h_2(key))\%M,i={1,2,3,...,M} hc(key,i)=hashi=(hash0+i∗h2(key))%M,i=1,2,3,...,M
  • 要求 h 2 ( k e y ) < M h_2(key)<M h2(key)<M且 h 2 ( k e y ) h_2(key) h2(key)和M互为质数,有两种简单的取值方法:1、当M为2整数幂时, h 2 ( k e y ) h_2(key) h2(key)从[0,M-1]任选一个奇数;2、当M为质数时, h 2 ( k e y ) = k e y % ( M − 1 ) + 1 h_2(key)=key\%(M-1)+1 h2(key)=key%(M−1)+1
  • 保证 h 2 ( k e y ) h_2(key) h2(key)与M互质是因为根据固定的偏移量所寻址的所有位置将形成一个群,若最大公约数 p = g c d ( M , h 1 ( k e y ) ) > 1 p=gcd(M,h_1(key))>1 p=gcd(M,h1(key))>1,那么所能寻址的位置的个数为 M / P < M M/P<M M/P<M,使得对于一个关键字来说无法充分利用整个散列表。举例来说,若初始探查位置为1,偏移量为3,整个散列表大小为12,那么所能寻址的位置为{1, 4, 7, 10},寻址个数为 12 / g c d ( 12 , 3 ) = 4 12/gcd(12,3)=4 12/gcd(12,3)=4
  • 本质也还是跳跃探测,减少冲突堆积
1.5.2 除留余数法(哈希函数)+ 线性探测(开放定址法解决冲突)模拟实现

扩容

这里我们哈希表负载因子控制在0.7,当负载因子到0.7以后我们就需要扩容了,我们还是按照2倍扩容。(如果要实现保持表的大小为质数👉)在sgi版本的哈希表使用的方法,给了一个近似2倍的质数表,每次去质数表获取扩容后的大小。

key不能取模的问题

当key是string/Date等类型时,key不能取模,那么我们需要给HashTable增加一个仿函数,这个仿函数支持把key转换成一个可以取模的整形,如果key可以转换为整形并且不容易冲突,那么这个仿函数就用默认参数即可,如果这个Key不能转换为整形,我们就需要自己实现一个仿函数传给这个参数,实现这个仿函数的要求就是尽量key的每值都参与到计算中,让不同的key转换出的整形值不同。string做哈希表的key非常常见,所以我们可以考虑把string特化一下。

代码框架

c++ 复制代码
// 哈希函数采用除留余数法
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 *= 31;
			hash += e;
		}

		return hash;
	}
};

// 以下采用开放定址法,即线性探测解决冲突
namespace open_address
{
    enum State
	{
		EXIST,
		EMPTY,
		DELETE
	};
    
    template<class K, class V>
	struct HashData
	{
		pair<K, V> _kv;
		State _state = EMPTY;
	};
    
    template<class K, class V, class Hash = HashFunc<K>>
	class HashTable
	{
	public:
		HashTable()
		{
			_tables.resize(10);
		}
        
        bool Insert(const pair<K, V>& kv);
        HashData<K, V>* Find(const K& key);
        bool Erase(const K& key);
        
    private:
		vector<HashData<K, V>> _tables;
		size_t _n = 0;  // 表中存储数据个数
	};
}

实现结果

c++ 复制代码
#pragma once
#include<string>
#include<vector>

using namespace std;

// 哈希函数采用除留余数法
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 *= 31;
			hash += e;
		}

		return hash;
	}
};

// 以下采用开放定址法,即线性探测解决冲突
namespace open_address
{
	enum State
	{
		EXIST,
		EMPTY,
		DELETE
	};

	template<class K, class V>
	struct HashData
	{
		pair<K, V> _kv;
		State _state = EMPTY;
	};

	template<class K, class V, class Hash = HashFunc<K>>
	class HashTable
	{
	public:
		HashTable()
		{
			_tables.resize(10);
		}

		bool Insert(const pair<K, V>& kv) {
			if (Find(kv.first))
				return false;

			if (_n / _tables.size() > 0.7) {
				HashTable<K, V> newtable;
				newtable._tables.resize(_tables.size() * 2);
				for (auto& e : _tables) {
					if (e._state == EXIST)
						newtable.Insert(e._kv);
				}
				_tables.swap(newtable._tables);
			}

			Hash hash;
			size_t k = hash(kv.first) % _tables.size();
			
			for (int i = 0; i < _tables.size(); ++i) {
				size_t nk = (k + i) % _tables.size();
				if (_tables[nk]._state != EXIST) {
					_tables[nk]._kv = kv;
					_tables[nk]._state = EXIST;
					++_n;
					return true;
				}
			}
			return false;
		}
		HashData<K, V>* Find(const K& key) {
			Hash hash;
			size_t k = hash(key) % _tables.size();
			for (int i = 0; i < _tables.size(); ++i) {
				size_t nk = (k + i) % _tables.size();
				if (_tables[nk]._state == EXIST
					&& _tables[nk]._kv.first == key) {
					return &_tables[nk];
				}
			}
			return nullptr;
		}
		bool Erase(const K& key) {
			HashData<K, V>* tmp = Find(key);
			if (!tmp)
				return false;

			tmp->_state = DELETE;
			return true;
		}

	private:
		vector<HashData<K, V>> _tables;
		size_t _n = 0;  // 表中存储数据个数
	};
}
1.5.3 链地址法

解决冲突的思路

开放定址法中所有的元素都放到哈希表里,链地址法中所有的数据不再直接存储在哈希表中,哈希表中存储一个指针,没有数据映射这个位置时,这个指针为空,有多个数据映射到这个位置时,我们把这些冲突的数据链接成一个链表,挂在哈希表这个位置下面,链地址法也叫做拉链法或者哈希桶。

扩容

开放定址法负载因子必须小于1,链地址法的负载因子就没有限制了,可以大于1。负载因子越大,哈希冲突的概率越高,空间利用率越高;负载因子越小,哈希冲突的概率越低,空间利用率越低;stl中unordered_xxx的最大负载因子基本控制在1,大于1就扩容,我们下面实现也使用这个方式。

极端场景

如果极端场景下,某个桶特别长怎么办?其实我们可以考虑使用全域散列法,这样就不容易被针对了。但是假设不是被针对了,用了全域散列法,但是偶然情况下,某个桶很长,查找效率很低怎么办?这里在Java8的HashMap中当桶的长度超过一定阀值(8)时就把链表转换成红黑树。一般情况下,不断扩容,单个桶很长的场景还是比较少的,下面实现就不搞这么复杂了。

1.5.4 除留余数法(哈希函数)+ 链地址法(冲突处理)模拟实现

代码框架

c++ 复制代码
namespace MySTL
{
	template<class T>
	struct HashNode
	{
		T _data;
		HashNode<T>* _next;
		HashNode(const T& data)
			:_data(data)
			, _next(nullptr)
		{
		}
	};


	// K 为 T 中key的类型
	// T 可能是键值对,也可能是K
	// KeyOfT: 从T中提取key
	// Hash将key转化为整形,因为哈希函数使用除留余数法
	template<class K, class T, class KeyOfT, class Hash>
	class HashTable
	{

		typedef HashNode<T> Node;
	public:
		HashTable()
		{
			_tables.resize(10, nullptr);
		}

		// 哈希桶的销毁
		~HashTable();

		// 插入值为data的元素,如果data存在则不插入
		bool Insert(const T& data);

		// 在哈希桶中查找值为key的元素,存在返回true否则返回false
		bool Find(const K& key);

		// 哈希桶中删除key的元素,删除成功返回true,否则返回false
		bool Erase(const K& key);

	private:
		vector<Node*> _tables;  // 指针数组
		size_t _n = 0;			// 表中存储数据个数
	};
}

实现结果

c++ 复制代码
namespace MySTL
{
	template<class T>
	struct HashNode
	{
		T _data;
		HashNode<T>* _next;
		HashNode(const T& data)
			:_data(data)
			, _next(nullptr)
		{
		}
	};


	// K 为 T 中key的类型
	// T 可能是键值对,也可能是K
	// KeyOfT: 从T中提取key
	// Hash将key转化为整形,因为哈希函数使用除留余数法
	template<class K, class T, class KeyOfT, class Hash>
	class HashTable
	{

		typedef HashNode<T> Node;
	public:
		HashTable()
		{
			_tables.resize(10, nullptr);
		}

		// 哈希桶的销毁
		~HashTable() {
			for (int i = 0; i < _tables.size(); ++i) {
				Node* cur = _tables[i];
				while (cur) {
					Node* next = cur->_next;
					delete cur;
					cur = next;
				}

				_tables[i] = nullptr;
			}
		}

		// 插入值为data的元素,如果data存在则不插入
		bool Insert(const T& data) {
			Hash hash;
			KeyOfT kot;
			if (Find(kot(data)))
				return false;
			size_t idx = hash(kot(data)) % _tables.size();

			if (_n == _tables.size()) {
				vector<Node*> newtable(_tables.size() * 2, nullptr);
				for (int i = 0; i < _tables.size(); ++i) {
					Node* cur = _tables[i];
					while (cur) {
						Node* next = cur->_next;
						
						size_t idx = hash(kot(cur->_data)) % newtable.size();
						cur->_next = newtable[idx];
						newtable[idx] = cur;

						cur = next;
					}
					_tables[i] = nullptr;
				}
				_tables.swap(newtable);
			}


			Node* newnode = new Node(data);
			newnode->_next = _tables[idx];
			_tables[idx] = newnode;
			++_n;
			return true;
		}

		// 在哈希桶中查找值为key的元素,存在返回true否则返回false
		bool Find(const K& key) {
			Hash hash;
			KeyOfT kot;
			size_t idx = hash(key) % _tables.size();
			Node* cur = _tables[idx];
			while (cur) {
				if (kot(cur->_data) == key) {
					return true;
				}
				cur = cur->_next;
			}
			return false;
		}

		// 哈希桶中删除key的元素,删除成功返回true,否则返回false
		bool Erase(const K& key) {
			Hash hash;
			KeyOfT kot;
			size_t idx = hash(key) % _tables.size();
			Node* parent = nullptr;
			Node* cur = _tables[idx];
			while (cur) {
				if (kot(cur->_data) == key) {
					if (parent == nullptr) {
						_tables[idx] = cur->_next;
					}
					else {
						parent->_next = cur->_next;
					}
					
					delete cur;
					--_n;
					return true;
				}
				parent = cur;
				cur = parent->_next;
			}
			return false;
		}

	private:
		vector<Node*> _tables;  // 指针数组
		size_t _n = 0;			// 表中存储数据个数
	};
}

2. 用哈希表封装myunordered_map和myunordered_set

myunordered_map框架代码

c++ 复制代码
namespace MySTL
{
	// 为了实现简单,在哈希桶的迭代器类中需要用到hashBucket本身,
	template<class K, class V, class KeyOfValue, class HF>
	class HashBucket;

	// 注意:因为哈希桶在底层是单链表结构,所以哈希桶的迭代器不需要--操作
	template <class K, class V, class KeyOfValue, class HF>
	struct HBIterator
	{
		typedef HashBucket<K, V, KeyOfValue, HF> HashBucket;
		typedef HashBucketNode<V>* PNode;
		typedef HBIterator<K, V, KeyOfValue, HF> Self;

		HBIterator(PNode pNode = nullptr, HashBucket* pHt = nullptr);
		Self& operator++();
		Self operator++(int);
		V& operator*();
		V* operator->();
		bool operator==(const Self& it) const;
		bool operator!=(const Self& it) const;
		PNode _pNode;             // 当前迭代器关联的节点
		HashBucket* _pHt;         // 哈希桶--主要是为了找下一个空桶时候方便
	};

	// unordered_map中存储的是pair<K, V>的键值对,K为key的类型,V为value的类型,HF哈希函数类型
	// unordered_map在实现时,只需将hashbucket中的接口重新封装即可
	template<class K, class V, class HF = DefHashF<K>>
	class unordered_map
	{
		typedef HashBucket<K, pair<K, V>, KeyOfValue, HF> HT;
		// 通过key获取value的操作
		struct KeyOfValue
		{
			const K& operator()(const pair<K, V>& data)
			{
				return data.first;
			}
		};
	public:
		typename typedef HT::Iterator iterator;
	public:
		unordered_map() : _ht()
		{
		}
		////////////////////////////////////////////////////
		iterator begin() { return _ht.begin(); }
		iterator end() { return _ht.end(); }
		////////////////////////////////////////////////////////////
		// capacity
		size_t size()const { return _ht.size(); }
		bool empty()const { return _ht.empty(); }
		///////////////////////////////////////////////////////////
		// Acess
		V& operator[](const K& key)
		{
			pair<iterator, bool> ret = _ht.InsertUnique(pair<K, V>(key, V()));
			return ret.fisrt->second;
		}
		const V& operator[](const K& key)const;
		//////////////////////////////////////////////////////////
		// lookup
		iterator find(const K& key) { return _ht.Find(key); }
		size_t count(const K& key) { return _ht.Count(key); }
		/////////////////////////////////////////////////
		// modify
		pair<iterator, bool> insert(const pair<K, V>& valye)
		{
			return _ht.Insert(valye);
		}

		iterator erase(iterator position)
		{
			return _ht.Erase(position);
		}
		////////////////////////////////////////////////////////////
		// bucket
		size_t bucket_count() { return _ht.BucketCount(); }
		size_t bucket_size(const K& key) { return _ht.BucketSize(key); }
	private:
		HT _ht;
	};
}

myunordered_set框架代码

c++ 复制代码
namespace MySTL
{
	// 为了实现简单,在哈希桶的迭代器类中需要用到hashBucket本身,
	template<class K, class V, class KeyOfValue, class HF>
	class HashBucket;

	// 注意:因为哈希桶在底层是单链表结构,所以哈希桶的迭代器不需要--操作
	template <class K, class V, class KeyOfValue, class HF>
	struct HBIterator
	{
		typedef HashBucket<K, V, KeyOfValue, HF> HashBucket;
		typedef HashBucketNode<V>* PNode;
		typedef HBIterator<K, V, KeyOfValue, HF> Self;

		HBIterator(PNode pNode = nullptr, HashBucket* pHt = nullptr);
		Self& operator++()
		{
			// 当前迭代器所指节点后还有节点时直接取其下一个节点
			if (_pNode->_pNext)
				_pNode = _pNode->_pNext;
			else
			{
				// 找下一个不空的桶,返回该桶中第一个节点
				size_t bucketNo = _pHt->HashFunc(KeyOfValue()(_pNode->_data)) + 1;
				for (; bucketNo < _pHt->BucketCount(); ++bucketNo)
				{
					if (_pNode = _pHt->_ht[bucketNo])
						break;
				}
			}

			return *this;
		}
		Self operator++(int);
		V& operator*();
		V* operator->();
		bool operator==(const Self& it) const;
		bool operator!=(const Self& it) const;
		PNode _pNode;             // 当前迭代器关联的节点
		HashBucket* _pHt;         // 哈希桶--主要是为了找下一个空桶时候方便
	};

	// unordered_set中存储的是K类型,HF哈希函数类型
	// unordered_set在实现时,只需将hashbucket中的接口重新封装即可
	template<class K, class HF = DefHashF<K>>
	class unordered_set
	{
		typedef HashBucket<K, K, KeyOfValue, HF> HT;
		// 通过key获取value的操作
		struct KeyOfValue
		{
			const K& operator()(const K& data)
			{
				return data;
			}
		};
	public:
		typename typedef HT::Iterator iterator;
	public:
		unordered_set() : _ht()
		{}
		////////////////////////////////////////////////////
		iterator begin(){ return _ht.begin(); }
		iterator end(){ return _ht.end(); }
		////////////////////////////////////////////////////////////
		// capacity
		size_t size()const{ return _ht.size(); }
		bool empty()const{ return _ht.empty(); }
		///////////////////////////////////////////////////////////
		// lookup
		iterator find(const K& key){ return _ht.Find(key); }
		size_t count(const K& key){ return _ht.Count(key); }
		/////////////////////////////////////////////////
		// modify
		pair<iterator, bool> insert(const K& valye)
		{
			return _ht.Insert(valye);
		}

		iterator erase(iterator position)
		{
			return _ht.Erase(position);
		}
		////////////////////////////////////////////////////////////
		// bucket
		size_t bucket_count(){ return _ht.BucketCount(); }
		size_t bucket_size(const K& key){ return _ht.BucketSize(key); }
	private:
		HT _ht;
	};
}

实现结果

c++ 复制代码
// HashBucket.h
#pragma once
#include<string>
#include<vector>
#include<assert.h>

using namespace std;

namespace MySTL
{
	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 HashBucket;

	template<class K>
	class DefHashF {
	public:
		size_t operator()(const K& key) {
			return (size_t)key;
		}
	};

	template<>
	class DefHashF<string> {
	public:
		size_t operator()(const string& s) {
			// BKDR
			size_t hash = 0;
			for (auto ch : s)
			{
				hash += ch;
				hash *= 131;
			}

			return hash;
		}
	};

	template <class K, class V, class KeyOfValue, class HF>
	struct HBIterator
	{
		typedef HashBucket<K, V, KeyOfValue, HF> HashBucket;
		typedef HashNode<V>* PNode;
		typedef HBIterator<K, V, KeyOfValue, HF> Self;

		HBIterator(PNode pNode = nullptr, HashBucket* pHt = nullptr)
			: _pNode(pNode)
			, _pHt(pHt)
		{
		}

		Self& operator++() {
			if (_pNode->_next)
				_pNode = _pNode->_next;
			else {
				KeyOfValue kov;
				HF hf;

				size_t idx = (hf(kov(_pNode->_data)) + 1) % _pHt->_tables.size();
				_pNode = nullptr;
				for (size_t i = idx; i < _pHt->_tables.size(); ++i) {
					if (_pHt->_tables[i]) {
						_pNode = _pHt->_tables[i];
						break;
					}
				}
			}

			return *this;
		}
		Self operator++(int) {
			PNode pcur = _pNode;
			++_pNode;
			return pcur;
		}
		V& operator*() { return _pNode->_data; }
		V* operator->() { return &_pNode->_data; }
		bool operator==(const Self& it) const { return _pNode == it._pNode; }
		bool operator!=(const Self& it) const { return _pNode != it._pNode; }

		PNode _pNode;             // 当前迭代器关联的节点
		HashBucket* _pHt;         // 哈希桶--主要是为了找下一个空桶时候方便
	};

	// K 为 T 中key的类型
	// T 可能是键值对,也可能是K
	// KeyOfT: 从T中提取key
	// Hash将key转化为整形,因为哈希函数使用除留余数法
	template<class K, class T, class KeyOfT, class Hash>
	class HashBucket
	{
		template <class K, class V, class KeyOfValue, class HF>
		friend struct HBIterator;

		typedef HashNode<T> Node;
	public:
		typedef HBIterator<const K, T, KeyOfT, Hash> Iterator;
		typedef HBIterator<const K, const T, KeyOfT, Hash> ConstIterator;

		HashBucket()
		{
			_tables.resize(10, nullptr);
		}

		// 哈希桶的销毁
		~HashBucket() {
			for (int i = 0; i < _tables.size(); ++i) {
				Node* cur = _tables[i];
				while (cur) {
					Node* next = cur->_next;
					delete cur;
					cur = next;
				}

				_tables[i] = nullptr;
			}
		}

		Iterator begin() {
			for (size_t i = 0; i < _tables.size(); i++) {
				if (_tables[i]) {
					return { _tables[i], this };
				}
			}

			return { nullptr, this };
		}

		Iterator end() { return { nullptr, this }; }

		size_t size() { return _n; }

		size_t BucketCount() { return _tables.size(); }

		bool empty() { return _n == 0; }

		size_t Count(const K& key) {
			size_t cnt = 0;
			Iterator cur = Find(key);

			KeyOfT kot;
			while (cur != end()) {
				if (kot(*cur) == key)
					++cnt;
				++cur;
			}

			return cnt;
		}

		size_t BucketSize(const K& key) {
			Hash hash;
			size_t idx = hash(key) % _tables.size();

			size_t cnt = 0;
			Node* cur = _tables[idx];
			while (cur) {
				++cnt;
				cur = cur->_next;
			}

			return cnt;
		}

		pair<Iterator, bool> Insert(const T& data) {
			Hash hash;
			KeyOfT kot;
			Iterator tmp = Find(kot(data));
			if (tmp != end())
				return { tmp, false };
			size_t idx = hash(kot(data)) % _tables.size();

			if (_n == _tables.size()) {
				vector<Node*> newtable(_tables.size() * 2, nullptr);
				for (int i = 0; i < _tables.size(); ++i) {
					Node* cur = _tables[i];
					while (cur) {
						Node* next = cur->_next;

						size_t idx = hash(kot(cur->_data)) % newtable.size();
						cur->_next = newtable[idx];
						newtable[idx] = cur;

						cur = next;
					}
					_tables[i] = nullptr;
				}
				_tables.swap(newtable);
			}

			Node* newnode = new Node(data);
			newnode->_next = _tables[idx];
			_tables[idx] = newnode;
			++_n;
			return { { newnode, this }, true };
		}

		Iterator Find(const K& key) {
			Hash hash;
			KeyOfT kot;
			size_t idx = hash(key) % _tables.size();
			Node* cur = _tables[idx];
			while (cur) {
				if (kot(cur->_data) == key) {
					return { cur, this };
				}
				cur = cur->_next;
			}
			return { nullptr, this };
		}

		Iterator Erase(Iterator pos) {
			Hash hash;
			KeyOfT kot;

			if (Find(kot(*pos)) == end())
				assert(false);

			size_t idx = hash(kot(*pos)) % _tables.size();
			Node* parent = nullptr;
			Node* cur = _tables[idx];
			while (cur) {
				if (kot(cur->_data) == kot(*pos)) {
					if (parent == nullptr) {
						_tables[idx] = cur->_next;
					}
					else {
						parent->_next = cur->_next;
					}
					
					delete cur;
					--_n;
					return { parent->_next, *this };
				}
				parent = cur;
				cur = parent->_next;
			}

			return { nullptr, *this };
		}

	private:
		vector<Node*> _tables;  // 指针数组
		size_t _n = 0;			// 表中存储数据个数
	};
}
c++ 复制代码
// unordered_map.h
#pragma once

#include"HashBucket.h"

namespace MySTL
{
	// unordered_map中存储的是pair<K, V>的键值对,K为key的类型,V为value的类型,HF哈希函数类型
	// unordered_map在实现时,只需将hashbucket中的接口重新封装即可
	template<class K, class V, class HF = DefHashF<K>>
	class unordered_map
	{
		// 通过key获取value的操作
		struct KeyOfValue
		{
			const K& operator()(const pair<K, V>& data)
			{
				return data.first;
			}
		};
		typedef HashBucket<const K, pair<K, V>, KeyOfValue, HF> HT;
		
	public:
		typedef typename HT::Iterator iterator;
	public:
		unordered_map() : _ht()
		{
		}
		////////////////////////////////////////////////////
		iterator begin() { return _ht.begin(); }
		iterator end() { return _ht.end(); }
		////////////////////////////////////////////////////////////
		// capacity
		size_t size()const { return _ht.size(); }
		bool empty()const { return _ht.empty(); }
		///////////////////////////////////////////////////////////
		// Acess
		V& operator[](const K& key)
		{
			pair<iterator, bool> ret = _ht.Insert(pair<K, V>(key, V()));
			return ret.first->second;
		}
		const V& operator[](const K& key) const {
			pair<iterator, bool> ret = _ht.Insert(pair<K, V>(key, V()));
			return ret.first->second;
		}
		//////////////////////////////////////////////////////////
		// lookup
		iterator find(const K& key) { return _ht.Find(key); }
		size_t count(const K& key) { return _ht.Count(key); }
		/////////////////////////////////////////////////
		// modify
		pair<iterator, bool> insert(const pair<K, V>& value)
		{
			return _ht.Insert(value);
		}

		iterator erase(iterator position)
		{
			return _ht.Erase(position);
		}
		////////////////////////////////////////////////////////////
		// bucket
		size_t bucket_count() { return _ht.BucketCount(); }
		size_t bucket_size(const K& key) { return _ht.BucketSize(key); }
	private:
		HT _ht;
	};
}
c++ 复制代码
// unordered_set.h
#pragma once

#include"HashBucket.h"

namespace MySTL
{
	// unordered_set中存储的是K类型,HF哈希函数类型
	// unordered_set在实现时,只需将hashbucket中的接口重新封装即可
	template<class K, class HF = DefHashF<K>>
	class unordered_set
	{
		// 通过key获取value的操作
		struct KeyOfValue
		{
			const K& operator()(const K& data)
			{
				return data;
			}
		};
		typedef HashBucket<const K, K, KeyOfValue, HF> HT;
		
	public:
		typedef typename HT::Iterator iterator;
		typedef typename HT::ConstIterator const_iterator;
	public:
		unordered_set() : _ht()
		{
		}
		////////////////////////////////////////////////////
		iterator begin() { return _ht.begin(); }
		iterator end() { return _ht.end(); }
		////////////////////////////////////////////////////////////
		// capacity
		size_t size()const { return _ht.size(); }
		bool empty()const { return _ht.empty(); }
		///////////////////////////////////////////////////////////
		// lookup
		iterator find(const K& key) { return _ht.Find(key); }
		size_t count(const K& key) { return _ht.Count(key); }
		/////////////////////////////////////////////////
		// modify
		pair<iterator, bool> insert(const K& value)
		{
			return _ht.Insert(value);
		}

		iterator erase(iterator position)
		{
			return _ht.Erase(position);
		}
		////////////////////////////////////////////////////////////
		// bucket
		size_t bucket_count() { return _ht.BucketCount(); }
		size_t bucket_size(const K& key) { return _ht.BucketSize(key); }
	private:
		HT _ht;
	};
}

说明:有关ConstIterator尚未完全实现

相关推荐
Prince-Peng5 小时前
技术架构系列 - 详解Redis
数据结构·数据库·redis·分布式·缓存·中间件·架构
lxl13075 小时前
学习C++(5)运算符重载+赋值运算符重载
学习
zhuqiyua5 小时前
第一次课程家庭作业
c++
只是懒得想了5 小时前
C++实现密码破解工具:从MD5暴力破解到现代哈希安全实践
c++·算法·安全·哈希算法
ruxshui5 小时前
个人笔记: 星环Inceptor/hive普通分区表与范围分区表核心技术总结
hive·hadoop·笔记
码农水水5 小时前
得物Java面试被问:消息队列的死信队列和重试机制
java·开发语言·jvm·数据结构·机器学习·面试·职场和发展
慾玄5 小时前
渗透笔记总结
笔记
m0_736919105 小时前
模板编译期图算法
开发语言·c++·算法
玖釉-5 小时前
深入浅出:渲染管线中的抗锯齿技术全景解析
c++·windows·图形渲染
【心态好不摆烂】5 小时前
C++入门基础:从 “这是啥?” 到 “好像有点懂了”
开发语言·c++