【C++】STL —— 用哈希表同时封装出unordered_set和unordered_map

目录

一、底层结构

1. 哈希的概念 

二、哈希冲突

三、哈希函数 

四、解决哈希冲突 

1. 闭散列(开放定址法) 

1. 线性探测

2. 二次探测 

2. 闭散列的实现  

3. 开散列(拉链法)

4. 开散列和闭散列的比较

五、HashTable的改造 

六、unordered_set的模拟实现

七、unordered_smap的模拟实现


一、底层结构

unordered系列的关联式容器之所以效率比较高,是因为其底层使用了哈希结构。 

1. 哈希的概念 

        顺序结构以及平衡树中,元素关键码与其存储位置之间没有对应的关系,因此在查找一个元素时,必须要经过关键码的多次比较。顺序查找时间复杂度为O(N),平衡树中为树的高度,即O( logN ),搜索的效率取决于搜索过程中元素的比较次数。

        理想的搜索方法:可以不经过任何比较,一次直接从表中得到要搜索的元素。 如果构造一种存储结构,通过某种函数(hashFunc)使元素的存储位置与它的关键码之间能够建立一一映射的关系,那么在查找时通过该函数可以很快找到该元素。当向该结构中:

插入元素

  • 根据待插入元素的关键码,以此函数计算出该元素的存储位置并按此位置进行存放

搜索元素

  • 对元素的关键码进行同样的计算,把求得的函数值当做元素的存储位置,在结构中按此位置取元素比较,若关键码相等,则搜索成功

该方式即为哈希(散列)方法,哈希方法中使用的转换函数称为哈希(散列)函数,构造出来的结构称为哈希表(Hash Table)(或者称散列表)

例如:数据集合{1,7,6,4,5,9}
哈希函数设置为:hash(key) = key % capacity; capacity为存储元素底层空间总的大小。
我们将数据映射到capacity为10的哈希表中如下:

 

用该方法进行搜索不必进行多次关键码的比较,因此搜索的速度比较快
问题:按照上述哈希方式,向集合中插入元素44,会出现什么问题?(会出现哈希冲突)

二、哈希冲突

        从下图可以看出,集合中的元素1, 4, 5, 6, 7, 9在进行同样的哈希函数时,都能找到对应的位置进行存储,但是当元素44进行哈希函数时,和之前集合中的元素4位置相同,对于这样的现象,我们称之为哈希冲突

总结:不同关键字通过相同哈希哈数计算出相同的哈希地址,该种现象称为哈希冲突或哈希碰撞

三、哈希函数 

引起哈希冲突的一个原因可能是:哈希函数设计不够合理。 哈希函数设计原则:

  • 哈希函数的定义域必须包括需要存储的全部关键码,而如果散列表允许有m个地址时,其值域必须在0到m-1之间
  • 哈希函数计算出来的地址能均匀分布在整个空间中
  • 哈希函数应该比较简单

常见的哈希函数:

1. 直接定制法--(常用)
        取关键字的某个线性函数为散列地址:Hash(Key)= A*Key + B 优点:简单、均匀 缺点:需要事先知道关键字的分布情况 使用场景:适合查找比较小且连续的情况。
2. 除留余数法--(常用)
        设散列表中允许的地址数为m,取一个不大于m,但最接近或者等于m的质数p作为除数,按照哈希函数:Hash(key) = key% p(p<=m),将关键码转换成哈希地址。
3. 平方取中法--(了解)
        假设关键字为1234,对它平方就是1522756,抽取中间的3位227作为哈希地址; 再比如关键字为4321,对它平方就是18671041,抽取中间的3位671(或710)作为哈希地址。
平方取中法比较适合:不知道关键字的分布,而位数又不是很大的情况。
4. 折叠法--(了解)
        折叠法是将关键字从左到右分割成位数相等的几部分(最后一部分位数可以短些),然后将这几部分叠加求和,并按散列表表长,取后几位作为散列地址。
折叠法适合事先不需要知道关键字的分布,适合关键字位数比较多的情况。
5. 随机数法--(了解)
        选择一个随机函数,取关键字的随机函数值为它的哈希地址,即H(key) = random(key),其中random为随机数函数。 通常应用于关键字长度不等时采用此法。
注意:哈希函数设计的越精妙,产生哈希冲突的可能性就越低,但是无法避免哈希冲突

四、解决哈希冲突 

1. 闭散列(开放定址法) 

        闭散列:也叫开放定址法,当发生哈希冲突时,如果哈希表未被装满,说明在哈希表中必然还有空位置,那么可以把key存放到冲突位置中的“下一个” 空位置中去。那如何寻找下一个空位置呢?

1. 线性探测

线性探测:从发生冲突的位置开始,依次向后探测,直到寻找到下一个空位置为止。 

        上图只是一个元素产生了位置冲突,如果有多个元素与4这个位置产生冲突,那么后插入的元素就会把其他空位置给占了,就会导致你占我的,我占别人的情况,为了解决这样的问题,我们需要引入负载因子

负载因子 = 表中的有效数据 / 空间的大小。

  1. 负载因子越大,产生冲突的概率越大,增删查改的效率低,空间浪费越少;
  2. 负载因子越小,产生冲突的概率越小,增删查改的效率高,空间浪费越大;

        从上图可以看出,当哈希表的空间变为20时,插入了一些冲突的值(在哈希表空间为10的时候是产生冲突的),但是发现冲突减少了;

        对于闭散列来说,负载因子是特别重要的因素,一般控制在0.7~0.8以下,超过0.8会导致在查表时CPU缓存不命中按照曲线上升。
线性探测的优点:实现简单
缺点:发生冲突,容易产生数据堆积,出现踩踏,导致搜索效率低。

2. 二次探测 

        线性探测的缺陷是产生冲突的数据堆积在一块,这与其找下一个空位置有关系,因为找空位置的方式就 是挨着往后逐个去找,因此二次探测为了避免该问题,找下一个空位置的方法为:Hash(key) = key % len + i ^2;(i=0,1,2…)

 通过线性探测和二次探测的比较,我们发现哈希冲突明显好了很多;

2. 闭散列的实现  

        采用闭散列处理哈希冲突时,不能随便物理删除哈希表中已有的元素,若直接删除元素会影响其他元素的搜索。比如删除元素11,如果直接删除掉,21查找起来可能会受影响。因此线性探测采用标记的伪删除法来删除一个元素。 

 

        11和21是和1冲突,从1开始找,找到11后并删除。紧接着去找21,但是遍历到2后面是一个空,但是21还在表中,不可能遍历一遍哈希表,这样就是去了哈希表的意义了。因此要在哈希表中加上状态。当哈希表中删除一个元素后,我们不应该简单的将状态设为EMPTY,要将该位置的状态设为DELETE。在查找的过程中,如果当前位置和查找的Key值不相等,但是当前位置的状态是EXIST或者是DELETE,我们都要往后查找,而当我们插入时,可以插入到状态EMPTY和DELETE上。

enum Status//标识哈希表中每个元素的状态
{
	EXIST,  // 无数据的空位置
	EMPTY,  // 已存储数据
	DELETE, // 原本有数据,但是被删除了
};

代码如下:

namespace CloseHash
{
	enum Status//标识哈希表元素的状态
	{
		EXIST,   //无数据的空位置
		EMPTY,   //已存储数据
		DELETE,  //原本有数据,但是被删除了
	};

	//哈希表的结构
	template<class K, class V>
	struct HashData
	{
		pair<K, V> _kv;
		Status _status = EMPTY;
	};
	//哈希表提供的仿函数(支持string类型,走的是特化的版本)
	template<class K>
	struct Hash
	{
		size_t operator()(const K& key)
		{
			return key;
		}
	};
	
	template<>//特化
	struct Hash<string>
	{
		//BKDR哈希
		size_t operator()(const string& s)
		{
			size_t value = 0;
			for (auto ch : s)
			{
				value *= 31;
				value += ch;
			}
			return value;
		}
	};
    //哈希表的实现(kv模型和缺省的仿函数)
	template<class K, class V , class HashFunc = Hash<K>>
	class HashTable
	{
	public:
        //哈希表的删除
		bool Erase(const K& key)
		{
			HashData<K, V>* ret = Find(key);
			if (ret == nullptr)
			{
				return false;
			}
			else
			{
				--_n;
				ret->_status = DELETE;
				return true;
			}
		}

        //哈希表的查找
		HashData<K, V>* Find(const K& key)
		{
			if (_tables.size() == 0)
			{
				return nullptr;
			}
	
			HashFunc hf;
			size_t start = hf(key) % _tables.size();
			size_t i = 0;
			size_t index = start;
			while (_tables[index]._status != EMPTY)
			{
				if (_tables[index]._kv.first == key && _tables[index]._status == EXIST)
				{
					return &_tables[index];
				}
	
				++i;
				index = start + i;//线性探测
				//index = start + i*i;//二次探测
				index %= _tables.size();
			}
			return nullptr;
		}

        //哈希表的插入
		bool Insert(const pair<K, V>& kv)
		{
			HashData<K, V>* ret = Find(kv.first);
			if (ret)
			{
				return false;
			}
			//负载因子到0.7就扩容
			//负载因子越小,冲突概率越低,效率越高,空间浪费越多
			//负载因子越大,冲突概率越高,效率越低,空间浪费越少
			if (_tables.size() == 0 || _n * 10 / _tables.size() >= 7)
			{
				//扩容
				size_t newSize = _tables.size() == 0 ? 10 : _tables.size() * 2;
				HashTable<K, V, HashFunc> newHT;
				newHT._tables.resize(newSize);
				for (size_t i = 0; i < _tables.size(); ++i)
				{
					if (_tables[i]._status == EXIST)
					{
						newHT.Insert(_tables[i]._kv);
					}
				}
				_tables.swap(newHT._tables);
			}
	
			HashFunc hf;
			size_t start = hf(kv.first) % _tables.size();
			size_t i = 0;
			size_t index = start;
			//线性探测
			while (_tables[index]._status == EXIST)
			{
				++i;
				index = start + i;//线性探测
				//index = start + i*i;//二次探测
				index %= _tables.size();
			}
			_tables[index]._kv = kv;
			_tables[index]._status = EXIST;
			++_n;
			return true;
		}
	private:
		vector<HashData<K, V>> _tables;
		size_t _n = 0;//有效数据个数
	};
}

3. 开散列(拉链法)

        开散列法又叫链地址法(开链法),首先对关键码集合用散列函数计算散列地址,具有相同地址的关键码归于同一子集合,每一个子集合称为一个桶,各个桶中的元素通过一个单链表链接起来,各链表的头结点存储在哈希表中

代码实现: 

namespace LinkHash 
{
	template<class K>
	struct Hash
	{
		size_t operator()(const K& key)
		{
			return key;
		}
	};

	template<>//特化
	struct Hash<string>
	{
		//BKDR哈希
		size_t operator()(const string& s)
		{
			size_t value = 0;
			for (auto ch : s)
			{
				value *= 31;
				value += ch;
			}
			return value;
		}
	};
	template<class K, class V>
	struct HashNode
	{
		pair<K, V> _kv;
		HashNode<K, V>* _next;
		HashNode(const pair<K, V>& kv)
			:_kv(kv)
			, _next(nullptr)
		{}
	};
	template<class K, class V, class HashFunc = Hash<K>>
	class HashTable
	{
		typedef HashNode<K, V> Node;
	public:
        //删除
		bool Erase(const K& key)
		{
			if (_tables.empty())//如果号系表为空,直接返回false
			{
				return false;
			}
            
			HashFunc hf;//定义仿函数对象
			size_t index = hf(key) % _tables.size();//通过哈希函数计算出对应的哈希桶编号index
			Node* cur = _tables[index];
			Node* prev = nullptr;
			while (cur)//遍历哈希桶,也就是遍历单链表
			{
				if (cur->_kv.first == key)
				{
					if (prev == nullptr)//头删
					{
						_tables[index] = cur->_next;
					}
					else//中间删除
					{
						prev->_next = cur->_next;
					}
					--_n;
					delete cur;
					return true;
				}
				else
				{
					prev = cur;
					cur = cur->_next;
				}
			}
			return false;
		}


        //查找
		Node* Find(const K& key)
		{
			if (_tables.empty())//如果哈希表为空,则直接返回
			{
				return nullptr;
			}
			HashFunc hf;//定义仿函数对象
			size_t index = hf(key) % _tables.size();//通过哈希函数计算出对应的哈希桶编号index
			Node* cur = _tables[index];
			while (cur)//遍历哈希桶
			{
				if (cur->_kv.first == key)
				{
					return cur;
				}
				else
				{
					cur = cur->_next;
				}
			}
			return nullptr;
		}
        //哈希表在扩容时,采用素数序列进行扩容
        size_t GetNextPrime(size_t num)
        {
            //素数序列
	        static const unsigned long __stl_prime_list[28] =
	        {
		        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
	        };
	        for (size_t i = 0; i < 28; i++)
	        {
		        if (__stl_prime_list[i] > num)
		        {
			        return __stl_prime_list[i];
		        }
	        }
            return __stl_prime_list[27];
        }


        //插入
		bool Insert(const pair<K, V>& kv)
		{
			HashFunc hf;
			Node* ret = Find(kv.first);//插入元素之前,首先进行查找,如果存在,则不允许插入
			if (ret)
			{
				return false;
			}

			//负载因子 == 1时就扩容
			if (_n == _tables.size())//哈希表的大小为0,或负载因子超过1
			{
				size_t newSize = GetNextPrime(_tables.size());
				vector<Node*> newTables;
				newTables.resize(newSize);
				for (size_t i = 0; i < _tables.size(); ++i)
				{
					Node* cur = _tables[i];
					while (cur)
					{
						Node* next = cur->_next;
						size_t index = hf(cur->_kv.first) % newTables.size();
						//头插
						cur->_next = newTables[index];
						newTables[index] = cur;
						cur = next;
					}
					_tables[i] = nullptr;
				}
				_tables.swap(newTables);
			}
			size_t index = hf(kv.first) % _tables.size();
			Node* newnode = new Node(kv);
			newnode->_next = _tables[index];
			_tables[index] = newnode;
			++_n;
			return true;
		}
	private:
		vector<Node*> _tables;
		size_t _n = 0;//有效的数据个数
	};
}

4. 开散列和闭散列的比较

        应用链地址法处理溢出,需要增设链接指针,似乎增加了存储开销。事实上: 由于开地址法必须保持大量的空闲空间以确保搜索效率,如二次探查法要求装载因子a <= 0.7,而表项所占空间又比指针大的多,所以使用链地址法反而比开地址法节省存储空间。

五、HashTable的改造 

开散列增容的问题:

        桶的个数是一定的,随着元素的不断插入,每个桶中元素的个数不断增多,极端情况下,可能会导致一个桶中链表节点非常多,会影响的哈希表的性能,因此在一定条件下需要对哈希表进行增容,那该条件怎么确认呢?开散列最好的情况是:每个哈希桶中刚好挂一个节点,再继续插入元素时,每一次都会发 生哈希冲突,因此,在元素个数刚好等于桶的个数时,可以给哈希表增容。
#include <iostream>
#include <vector>
#include <string>
using namespace std;

template<class K>
struct Hash
{
	size_t operator()(const K& key)
	{
		return key;
	}
};

template<>//特化
struct Hash<string>
{
	//BKDR哈希
	size_t operator()(const string& s)
	{
		size_t value = 0;
		for (auto ch : s)
		{
			value *= 31;
			value += ch;
		}
		return value;
	}
};
namespace LinkHash 
{
	
	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 HashFunc>
	class HashTable;

	template<class K, class T, class Ref, class Ptr, class KeyOfT, class HashFunc>
	struct __HTIterator
	{
		typedef HashNode<T> Node; 
		typedef __HTIterator<K, T, Ref, Ptr, KeyOfT, HashFunc> Self;
		Node* _node;
		HashTable<K, T, KeyOfT, HashFunc>* _pht;
		
		__HTIterator(Node* node, HashTable<K, T, KeyOfT, HashFunc>* pht)
			:_node(node)
			, _pht(pht)
		{}
		Ref operator*()
		{
			return _node->_data;
		}
		Ptr operator->()
		{
			return &_node->_data;
		}
		//前置++
		Self& operator++()
		{
			if (_node->_next)
			{
				_node = _node->_next;
			}
			else
			{
				KeyOfT kot;
				HashFunc hf;
				size_t index = hf(kot(_node->_data)) % _pht->_tables.size();
				++index;
				//找下一个不为空的桶
				while (index < _pht->_tables.size())
				{
					if (_pht->_tables[index] != nullptr) 
						break;
					else 
						++index;
				}
				//表走完了都没有找到下一个桶
				if (index == _pht->_tables.size())
				{
					_node = nullptr;
				}
				else
				{
					_node = _pht->_tables[index];
				}
			}
			return *this;
		}

		bool operator!=(const Self& s)
		{
			return _node != s._node;
		}
		bool operator==(const Self& s)
		{
			return _node == s._node;
		}

	};

	template<class K, class T, class KeyOfT, class HashFunc>
	class HashTable
	{
		typedef HashNode<T> Node;
		template<class K, class T, class Ref, class Ptr, class KeyOfT, class HashFunc>
		friend struct __HTIterator;
		typedef HashTable<K, T, KeyOfT, HashFunc>& Self;
	public:
		typedef __HTIterator<K, T, T&, T*, KeyOfT, HashFunc> iterator;
		//HashTable(){}
		HashTable() = default;//显示指定编译器去生产默认构造函数
		HashTable(const Self& ht)
		{
			_tables.resize(ht._tables.size());
			for (int i = 0; i < ht._tables.size(); i++)
			{
				Node* cur = ht._tables[i];
				while (cur) 
				{
					Node* copy = new Node(cur->_data);
					copy->_next = _tables[i];
					_tables[i] = copy;
					cur = cur->_next;
				}
			}
		}
		//ht1 = ht2
		Self& operator=(Self copy)
		{
			swap(_n, copy._n);
			_tables.swap(copy._tables);
			return *this;
		}
		~HashTable()
		{
			for (size_t i = 0; i < _tables.size(); i++)
			{
				Node* cur = _tables[i];
				while (cur)
				{
					Node* next = cur->_next;
					delete cur;
					cur = next;
				}
			}
		}
		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);
		}
		bool Erase(const K& key)
		{
			if (_tables.empty())
			{
				return false;
			}
			HashFunc hf;
			size_t index = hf(key) % _tables.size();
			Node* cur = _tables[index];
			Node* prev = nullptr;
			KeyOfT kot;
			while (cur)
			{
				if (kot(cur->_data) == key)
				{
					if (prev == nullptr)//头删
					{
						_tables[index] = cur->_next;
					}
					else//中间删除
					{
						prev->_next = cur->_next;
					}
					--_n;
					delete cur;
					return true;
				}
				else
				{
					prev = cur;
					cur = cur->_next;
				}
			}
			return false;
		}
		iterator Find(const K& key)
		{
			if (_tables.empty())
			{
				return end();
			}
			HashFunc hf;
			size_t index = hf(key) % _tables.size();
			Node* cur = _tables[index];
			KeyOfT kot;
			while (cur)
			{
				if (kot(cur->_data) == key)
				{
					return iterator(cur, this);
				}
				else
				{
					cur = cur->_next;
				}
			}
			return end();
		}

		size_t GetNextPrime(size_t num)
		{
			static const unsigned long __stl_prime_list[28] =
			{
				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
			};
			for (size_t i = 0; i < 28; i++)
			{
				if (__stl_prime_list[i] > num)
				{
					return __stl_prime_list[i];
				}
			}
			return __stl_prime_list[27];
		}

		pair<iterator, bool> Insert(const T& data)
		{
			HashFunc hf;
			KeyOfT kot;
			iterator ret = Find(kot(data));
			if (ret != end())
			{
				return make_pair(ret, false);
			}
			//负载因子 == 1时就扩容
			if (_n == _tables.size())
			{
				//size_t newSize = _tables.size() == 0 ? 10 : _tables.size() * 2;
				size_t newSize = GetNextPrime(_tables.size());
				vector<Node*> newTables;
				newTables.resize(newSize);
				for (size_t i = 0; i < _tables.size(); ++i)
				{
					Node* cur = _tables[i];
					while (cur)
					{
						Node* next = cur->_next;
						size_t index = hf(kot(cur->_data)) % newTables.size();
						//头插
						cur->_next = newTables[index];
						newTables[index] = cur;
						cur = next;
					}
					_tables[i] = nullptr;
				}
				_tables.swap(newTables);
			}
			size_t index = hf(kot(data)) % _tables.size();
			Node* newnode = new Node(data);
			newnode->_next = _tables[index];
			_tables[index] = newnode;
			++_n;
			//return true;
			return make_pair(iterator(newnode, this), false);
		}
	private:
		vector<Node*> _tables;
		size_t _n = 0;//有效的数据个数
	};
	void TestHashTable()
	{
		
	}
}

六、unordered_set的模拟实现

#include "HashTable.h"

namespace mlg
{
	template<class K, class hash = Hash<K>>
	class unordered_set
	{
		struct SetKeyOfT
		{
			const K& operator()(const K& key)
			{
				return key;
			}
		};
	public:
		typedef typename LinkHash::HashTable<K, K, SetKeyOfT, hash>::iterator iterator;
		iterator begin()
		{
			return _ht.begin();
		}
		iterator end()
		{
			return _ht.end();
		}
		pair<iterator, bool> insert(const K& key)
		{
			return _ht.Insert(key);
		}

	private:
		LinkHash::HashTable<K, K, SetKeyOfT, hash> _ht;
	};
}

七、unordered_smap的模拟实现

#include "HashTable.h"

namespace mlg
{
	template<class K, class V, class hash = Hash<K>>
	class unordered_map
	{
		struct MapKeyOfT
		{
			const K& operator()(const pair<K, V>& kv)
			{
				return kv.first;
			}
		};
	public:
		typedef typename LinkHash::HashTable<K, pair<K, V>, MapKeyOfT, hash>::iterator iterator;
		iterator begin()
		{
			return _ht.begin();
		}
		iterator end()
		{
			return _ht.end();
		} 
		V& operator[](const K& key)
		{
			auto ret = _ht.Insert(make_pair(key, V())); 
			return ret.first->second;
		}

		pair<iterator, bool> insert(const pair<K, V>& kv)
		{
			return _ht.Insert(kv);
		}
	private:
		LinkHash::HashTable<K, pair<K, V>, MapKeyOfT, hash> _ht;
		
	};
}

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霄沫凡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值