C++:哈希结构(内含unordered_set和unordered_map实现)

unordered系列关联式容器

在C++98中,STL提供了底层为红黑树结构的一系列关联式容器,在查询时效率可达到$log_2 N$,即最差情况下需要比较红黑树的高度次,当树中的节点非常多时,查询效率也不理想。最好 的查询是,进行很少的比较次数就能够将元素找到,因此在C++11中,STL又提供了4个 unordered系列的关联式容器,这四个容器与红黑树结构的关联式容器使用方式基本类似,只是 其底层结构不同,本文中只对unordered_map和unordered_set进行介绍。

unordered_map和unordered_set的文档介绍

1. unordered_map是存储键值对的关联式容器,其允许通过keys快速的索引到与 其对应的value。

2. 在unordered_map中,键值通常用于惟一地标识元素,而映射值是一个对象,其内容与此 键关联。键和映射值的类型可能不同。

3. 在内部,unordered_map没有对按照任何特定的顺序排序, 为了能在常数范围内 找到key所对应的value,unordered_map将相同哈希值的键值对放在相同的桶中。

4. unordered_map容器通过key访问单个元素要比map快,但它通常在遍历元素子集的范围迭 代方面效率较低。

5. unordered_maps实现了直接访问操作符(operator[]),它允许使用key作为参数直接访问 value。

6. 它的迭代器至少是前向迭代器。

详情可以参考文档:

https://cplusplus.com/reference/unordered_set/unordered_set/?kw=unordered_set

底层结构

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

哈希概念

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

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

当向该结构中:

插入元素

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

搜索元素

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

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

例如:数据集合{1,7,6,4,5,9};

哈希函数设置为:hash(key) = key % capacity;

capacity为存储元素底层空间总的大小。

常见哈希函数

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)作为哈希地址 平方取中法比较适合:不知道关键字的分布,而位数又不是很大的情况

直接定址法,需要是整型,且范围需要高度集中,除留余数法正是为了突破直接定址法的局限才被提出来,但是也引入了新的问题——哈希冲突。

注意:哈希函数设计的越精妙,产生哈希冲突的可能性就越低,但是无法避免哈希冲突。

哈希冲突

解决哈希冲突两种常见的方法是:闭散列和开散列

1. 开放地址法(闭散列) ,节点中含状态, 不能满,插入时要计算负载因子

2. 哈希桶/拉链法(开散列) 

如果不是整型,映射地址需要引入仿函数。

闭散列最大的缺陷就是空间利用率比较低,这也是哈希的缺陷。

闭散列实现

#pragma once
#include<iostream>
#include<vector>
#include<string>


using namespace std;

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

template<>
struct HashFunc<string>
{
	size_t  operator()(const string& k)
	{
		size_t ret = 0;
		for (const auto& e : k)
		{
			ret *= 131;
			ret += e;
		}
		return ret;
	}
};


namespace HashClose
{
	enum  state
	{
		EXIST,
		DELETE,
		EMPTY,
	};
	template<class K, class V>
	struct HashNode
	{
		pair<K, V> _kv;
		state _sta = EMPTY;
	};

	template<class K, class V, class Hash = HashFunc<K>>
	class HashTable
	{
	public:
		typedef HashNode<K, V>  Node;
		HashTable()
			:_table(10)
			,_n(0)
		{}

		Node* find(const K& k)
		{
			Hash hf;
			size_t hashi = hf(k) % _table.size();
			while (EMPTY != _table[hashi]._sta)
			{
				if (EXIST == _table[hashi]._sta && k == _table[hashi]._kv.first)
				{
					return &_table[hashi];
				}
				++hashi;
				hashi %= _table.size();
			}
			return nullptr;
		}

		bool  insert(const pair<K, V>& kv)
		{
			if (find(kv.first))
			{
				return false;
			}

			if (1.0 * _n / _table.size() >= 0.7)
			{
				HashTable newtable;
				newtable._table.resize(2 * _table.size());
				for(const auto& e : _table)
				{
					newtable.insert(e._kv);
				}
				_table.swap(newtable._table);
			}

			Hash hf;
			size_t hashi = hf(kv.first) % _table.size();
			while (EMPTY != _table[hashi]._sta)
			{
				++hashi;
				hashi %= _table.size();
			}
			_table[hashi]._sta = EXIST;
			_table[hashi]._kv = kv;

			++ _n;
		}

		bool erase(const K& key)
		{
			Node* ret = find(key);
			if (ret)
			{
				ret->_sta = DELETE;
				--_n;
				return true;
			}
			else
			{
				return false;
			}
		}

	private:
		vector<HashNode<K, V>> _table;
		size_t _n;
	};

	void testht1()
	{
		HashTable<int, int> ht;
		int a[] = { 18, 8, 7, 27, 57, 3, 38, 18 };
		for (auto e : a)
		{
			ht.insert(make_pair(e, e));
		}

		ht.insert(make_pair(17, 17));
		ht.insert(make_pair(5, 5));

		cout << ht.find(7) << endl;
		cout << ht.find(8) << endl;

		ht.erase(7);
		cout << ht.find(7) << endl;
		cout << ht.find(8) << endl;
	}

	void testht2()
	{
		string arr[] = { "苹果", "西瓜", "香蕉", "草莓", "苹果", "西瓜", "苹果", "苹果", "西瓜", "苹果", "香蕉", "苹果", "香蕉" };

		//HashTable<string, int, HashFuncString> countHT;
		HashTable<string, int> countHT;
		for (auto& e : arr)
		{
			HashNode<string, int>* ret = countHT.find(e);
			if (ret)
			{
				ret->_kv.second++;
			}
			else
			{
				countHT.insert(make_pair(e, 1));
			}
		}

		HashFunc<string> hf;
		cout << hf("abc") << endl;
		cout << hf("bac") << endl;
		cout << hf("cba") << endl;
		cout << hf("aad") << endl;
	}

}

开散列

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

 从上图可以看出,开散列中每个桶中放的都是发生哈希冲突的元素。

由于是一个数组下挂哈希桶,需要delete释放节点,需要写析构函数。

插入时头插。

扩容时旧节点重复利用

删除时与头节点交换,头删(也可以遍历直接删)

扩容时可以使容量为素数,以减少冲突

极端场景下,如果一个桶冲突过多,下面可以挂一个红黑树

开散列实现

namespace Hashbucket
{
	template<class T>
	struct  HashNode
	{
		HashNode(const T& t)
			:_date(t)
			,_next(nullptr)
		{}
		T _date;
		HashNode<T>* _next;
	};

	template<class K, class V, class Hash, class KeyOfV>
	class HashTable;

	template<class K, class V,class Ref, 
            class Ptr, class Hash, class KeyOfV, 
            class HTPTR, class HNPTR>
	struct HashIterator
	{
		typedef HashIterator<K, V, Ref, Ptr, Hash, KeyOfV, HTPTR, HNPTR> Self;
		typedef HashIterator<K, V, V&, V*, Hash, KeyOfV, 
        HashTable<K, V, Hash, KeyOfV>*, HashNode<V>*> Iterator;

		HTPTR _ht;
		HNPTR _hn;

		HashIterator(HTPTR ht, HNPTR hn)
			:_ht(ht)
			,_hn(hn)
		{}

		HashIterator(const Iterator& it)
			:_ht(it._ht)
			, _hn(it._hn)
		{}

		Ref operator*()
		{
			return _hn->_date;
		}

		Ptr operator->()
		{
			return &(_hn->_date);
		}

		Self& operator++()
		{
			if (_hn->_next)
			{
				_hn = _hn->_next;
			}
			else
			{
				KeyOfV kov;
				size_t hashi = Hash()(kov(_hn->_date)) % _ht->_table.size();
				while (++hashi < _ht->_table.size())
				{
					if (_ht->_table[hashi])
					{
						_hn = _ht->_table[hashi];
						return *this;
					}
				}
				_hn = nullptr;
			}
			return *this;
		}

		bool operator!=(const Self& it)const
		{
			return it._hn != _hn;
		}

	};

	template<class K, class V, class Hash, class KeyOfV>
	class HashTable
	{
	public:
		template<class K, class V, class Ref, class Ptr, class Hash, class KeyOfV, class HTPTR, class HNPTR>
		friend struct HashIterator;

		typedef HashTable<K, V, Hash, KeyOfV>  Self;
		typedef HashNode<V>  Node;
		typedef HashIterator<K, V, V&, V*, Hash, KeyOfV, Self*, Node*>  iterator;
		typedef HashIterator<K, V, const V&, const V*, Hash, KeyOfV, const Self*, const Node*>  const_iterator;

		//默认构造
		HashTable()
			:_n(0)
		{
			_table.resize(9, nullptr);
		}

		HashTable(const Self& ht)
			:_n(0)
		{
			_table.resize(9, nullptr);
			for (const auto& e : ht)
			{
				insert(e);
			}
		}

		iterator begin()
		{
			for (int i = 0; i < _table.size(); ++i)
			{
				if (_table[i])
				{
					return iterator(this, _table[i]);
				}
			}
			return iterator(this, nullptr);
		}

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

		const_iterator begin()const
		{
			for (int i = 0; i < _table.size(); ++i)
			{
				if (_table[i])
				{
					return const_iterator(this, _table[i]);
				}
			}
			return const_iterator(this, nullptr);
		}

		const_iterator end()const
		{
			return const_iterator(this, nullptr);
		}

		iterator find(const K& key)
		{
			Hash hs;
			KeyOfV kot;
			size_t hashi = hs(key) % _table.size();
			Node* cur = _table[hashi];
			while (cur)
			{
				if (key == kot(cur->_date))
				{
					return iterator(this, cur);
				}
				cur = cur->_next;
			}
			return end();
		}

		//找到下一个要扩容的尺寸
		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
			};

			for (int i = 0; i < __stl_num_primes; ++i)
			{
				if (__stl_prime_list[i] > n)
				{
					return __stl_prime_list[i];
				}
			}

			return __stl_prime_list[__stl_num_primes - 1];
		}

		pair<iterator, bool> insert(const V& v)
		{
			KeyOfV kot;
			//已经存在,不需要插入
			iterator it = find(kot(v));
			if (end() != it)
			{
				return make_pair(it, false);
			}

			Hash hs;
			//负载因子超过1 ->  扩容
			if(_n == _table.size())
			{
				vector<Node*> newtable;
				newtable.resize(__stl_next_prime(_table.size()), nullptr);

				for (int i = 0; i < _table.size(); ++i)
				{
					Node* cur = _table[i];
					_table[i] = nullptr;
					Node* pre = nullptr;
					while (cur)
					{
						size_t hashi = hs(kot(cur->_date)) % newtable.size();
						pre = cur;
						cur = cur->_next;
						pre-> _next = newtable[hashi];
						newtable[hashi] = pre;
					}
				}
				newtable.swap(_table);
			}
			//插入新节点
			 size_t hashi = hs(kot(v)) % _table.size();
			 Node* newnode = new Node(v);
			 newnode->_next = _table[hashi];
			 _table[hashi] = newnode;
			 ++_n;
			 return make_pair(iterator(this, newnode), true);
		}

	private:
		vector<Node*>  _table;
		size_t  _n;

	};

}

unordered_set和unordered_map

#pragma once
#include"hash.h"


namespace szg
{
	template<class K, class Hash = HashFunc<K>>
	class unordered_set
	{
	public:
		struct setKeyOfV
		{
			const K& operator()(const K& k)
			{
				return k;
			}
		};
		typedef typename Hashbucket::HashTable<K, K, HashFunc<K>, setKeyOfV>::const_iterator iterator;
		typedef typename Hashbucket::HashTable<K, K, HashFunc<K>, setKeyOfV>::const_iterator const_iterator;

		iterator begin()
		{
			return _ht.begin();
		}

		iterator end()
		{
			return _ht.end();
		}

		pair<iterator, bool> insert(const K& key)
		{
			return _ht.insert(key);
		}



	private:
		Hashbucket::HashTable<K, K, HashFunc<K>, setKeyOfV> _ht;

	};

}
#pragma once
#include"hash.h"
namespace szg
{
	template<class K, class V, class Hash = HashFunc<K>>
	class unordered_map
	{
	public:
		struct mapKeyOfV
		{
			const K& operator()(const pair<const K, V>& v)
			{
				return v.first;
			}
		};
		typedef typename Hashbucket::HashTable<K, pair<const K, V>, HashFunc<K>, mapKeyOfV>::iterator  iterator;
		typedef typename Hashbucket::HashTable<K, pair<const K, V>, HashFunc<K>, mapKeyOfV>::const_iterator  const_iterator;

		iterator begin()
		{
			return _ht.begin();
		}

		iterator end()
		{
			return _ht.end();
		}

		pair<iterator, bool> insert(const K& key)
		{
			return _ht.insert(key);
		}

		V& operator[](const K& key)
		{
			pair<iterator, bool> ret = _ht.insert(make_pair(key, V()));
			return ret.first->second;
		}



	private:
		Hashbucket::HashTable<K, pair<const K, V>, HashFunc<K>, mapKeyOfV> _ht;

	};

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

JDSZGLLL

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

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

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

打赏作者

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

抵扣说明:

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

余额充值