对于unordered_map和unordered_set底层哈希表的理解

哈希的概念

构造一种存储结构,通过某种函数(hashFunc)使元素的存储位置与它的关键码之间能够建立一一映射的关系,那么在查找时通过该函

数可以很快找到该元素。

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

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

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

 

哈希冲突 

对于两个数据元素的关键字 和 (i != j),有 != ,但有:Hash( ) == Hash( ),即:不同关键字通过相同哈希哈数计算出相同的哈希地址,该种现象称为哈希冲突或哈希碰撞。

 

哈希函数

哈希函数的定义域必须包括需要存储的全部关键码,而如果散列表允许有m个地址时,其值域必须在0到m-1之间

哈希函数计算出来的地址能均匀分布在整个空间中

哈希函数应该比较简单

常见哈希函数

1. 直接定制法--(常用)

取关键字的某个线性函数为散列地址:Hash(Key)= A*Key + B 优点:简单、均匀 缺点:需要事先

知道关键字的分布情况 使用场景:适合查找比较小且连续的情况。

2. 除留余数法--(常用)

设散列表中允许的地址数为m,取一个不大于m,但最接近或者等于m的质数p作为除数,按照哈希函

数:Hash(key) = key% p(p<=m),将关键码转换成哈希地址。

 

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

闭散列:

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

其中使用线性探测:从发生冲突的位置开始,依次向后探测,直到寻找到下一个空位置为止。来解决其中哈希冲突的问题。

闭散列哈希的简单实现:

namespace CLOSE_HASH
{
	enum State
	{
		EXITS,
		EMPTY,
		DELETE,
	};

	template<class T>
	struct HashData
	{
		T _data;
		State _state; // 状态
	};

	template<class K, class V>
	class HashTable
	{
		typedef HashData<pair<K, V>> HashData;
	public:

		pair<HashData*, bool> Insert(const pair<K, V>& kv)
		{
			// 假设要求负载因子控制在0.7
			if (_tables.size() == 0 || _dataNum * 10 / _tables.size() == 7)
			{
				size_t newSize = _tables.size() == 0 ? 10 : _tables.size() * 2;
				HashTable<K, V> newht;
				newht._tables.resize(newSize);
				// 将旧表的数据重新计算位置,映射到新表
				for (size_t i = 0; i < _tables.size(); ++i)
				{
					if (_tables[i]._state == EXITS)
					{
						newht.Insert(_tables[i]._data);
					}
				}

				_tables.swap(newht._tables);
			}

			size_t start = kv.first % _tables.size();
			size_t index = start;
			size_t i = 1;

			// 二次探测 ->线性探测的优化
			while (_tables[index]._state == EXITS)
			{
				if (_tables[index]._data.first == kv.first)
				{
					return make_pair(&_tables[index], false);
				}

				index = start + i*i;
				index %= _tables.size();
				++i;
			}

			_tables[index]._data = kv;
			_tables[index]._state = EXITS;
			++_dataNum;

			return make_pair(&_tables[index], true);
		}


		HashData* Find(const K& key)
		{
			size_t start = kv.first % _tables.size();
			size_t index = start;
			size_t i = 1;
			while (_tables[index]._state != EMPTY)
			{
				if (_tables[index]._state == EXITS
					&& _tables[index]._data.first == key)
				{
					return &_tables[index];
				}
				else
				{
					index = start + i*i;
					index %= _tables.size();
					++i;
				}
			}

			return nullptr;
		}


		void Erase(const K& key)//删除元素
		{
			HashData* ret = Find(key);
			if (ret)
			{
				ret->_state = DELETE;
			}
		}

		V& operator[](const K& key)
		{
			pair<HashData*, bool> ret = Insert(make_pair(key, V()));
			return ret.first->_data.second;
		}


	private:

		vector<HashData> _tables;
		size_t  _dataNum = 0;  // 有效的数据个数
	};


}

开散列

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

如果哈希冲突严重时,可以将红黑树连接到哈希表上来解决哈希冲突

代码实现:

namespace BUCKET_HASH
{


	template<class T>
	struct HashNode
	{
		HashNode<T>* _next;
		T _data;

		HashNode(const T& data)
			:_data(data)
			, _next(nullptr)
		{}
	};



	template<class K>//类型转换为了可以下面%运算
	struct _Hash
	{
		const K& operator()(const K& key)
		{
			return key;
		}
	};



 // bacd bcad 或者abc aad  字母加起来相等出现哈希冲突
 //将每个字母的ASCII*131然后相加可以减少这种字符串ASCII值%后结果相同的情况减少哈希冲突
	template<>
	struct _Hash<string>   
	{
		size_t operator()(const string& key)
		{
			//return key[0];
			size_t hash = 0;
			for (size_t i = 0; i < key.size(); ++i)
			{
				hash = hash * 131 + key[i];
			}

			return hash;
		}
	};

	
	// 前置声明
	template<class K, class T, class KeyOfT, class Hash>
  //V: 不同容器V的类型不同,如果是unordered_map,V代表一个键值对,如果是unordered_set,V 为 K
  //KeyOfValue: 因为V的类型不同,通过value取key的方式就不同
  //Hash哈希函数仿函数对象类型,哈希函数使用除留余数法,需要将Key转换为整形数字才能取模
	class HashTable;

	// 迭代器
	template<class K, class T, class KeyOfT, class Hash>
	struct HashTableIterator
	{
		typedef HashNode<T> Node;
		Node* _node;
		HashTable<K, T, KeyOfT, Hash>* _ht;
		typedef HashTableIterator<K, T, KeyOfT, Hash> Self;
		HashTableIterator(Node* node, HashTable<K, T, KeyOfT, Hash>* ht)
			:_node(node)
			, _ht(ht)
		{}


		 T operator*()
		 {
			 return _node->_data;
		 }
		 T * operator->()
		 {
			 return &_node->_data;

		 }
		iterator operator++()
		 {
			if (_node->_next != nullptr)
			{
				_node = _node->_next;//当前桶没有走完
			}
			else
			{
				KeyOfT kot;
				size_t index = _ht->HashFunc(kot(_node->_data), _ht->_tables.size());
				index++;
				for (; index < _ht->_tables.size(); ++ index)
				{
					Node *bucket = _ht->_tables[index];
					if (bucket)
					{
						_node = bucket;
						return *this;
						//break;
					}
				}
				_node = nullptr;
			}
			return *this;

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

	template<class K, class T, class KeyOfT, class Hash>
	class HashTable
	{
		typedef HashNode<T> Node;
		template<class K, class T, class KeyOfT, class Hash>;
		friend  struct  HashTableIterator;
	//因为在class HashTable中_tables和_dataNum都是私有的,迭代器无法使用,需要使用友元
	public:
		typedef HashTableIterator<K, T, KeyOfT, Hash> iterator;
		iterator begin()
		{
			for (size_t i = 0; i < _tables.size(); ++i)
			{
				Node* bucket = _tables[i];
				if (bucket)
				{
					return iterator(bucket, this);
				}
			}

			return end();
		}

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

		pair<Node*, bool> Insert(const T& data)
		{
			KeyOfT kot;

			// 负载因子控制到1 -> 平均下来每个桶挂1-2个数据
			if (_dataNum == _tables.size())
			{
				size_t newsize = _tables.size() == 0 ? 10 : _tables.size() * 2;
				vector<Node*> newtables;
				newtables.resize(newsize, nullptr);

				// 旧表的数据节点取下来,重新算在新表中的位置
				for (size_t i = 0; i < _tables.size(); ++i)
				{
					Node* cur = _tables[i];
					while (cur)
					{
						Node* next = cur->_next;

						// 头插到新表
						//size_t index = cur->_data.first % newtables.size();
						size_t index = HashFunc(kot(cur->_data), newtables.size());
						cur->_next = newtables[index];
						newtables[index] = cur;

						cur = next;
					}
					_tables[i] = nullptr;
				}

				_tables.swap(newtables);
			}

			size_t index = HashFunc(kot(data), _tables.size());
			// 查找key是否存在,存在则不插入。
			Node* cur = _tables[index];
			while (cur)
			{
				if (kot(cur->_data) == kot(data))
				{
					return make_pair(cur, false);
				}

				cur = cur->_next;
			}

			// 头插
			Node* newnode = new Node(data);
			newnode->_next = _tables[index];
			_tables[index] = newnode;
			++_dataNum;

			return make_pair(iterator (newnode,this), true);
		}

		// O(链式桶的长度)
		Node* Find(const K& key)
		{
			//size_t index = key % _tables.size();
			size_t index = HashFunc(key, _tables.size());

			Node* cur = _tables[index];
			while (cur)
			{
				if (cur->_data.first == key)
				{
					return cur;
				}
				else
				{
					cur = cur->_next;
				}
			}

			return nullptr;
		}

		bool Erase(const K& key)
		{
			//size_t index = key % _tables.size();
			size_t index = HashFunc(key, _tables.size());
			Node* prev = nullptr;
			Node* cur = _tables[index];
			while (cur)
			{
				if (cur->_data.first == key)
				{
					//if (prev == nullptr)
					if (cur == _tables[index])
						_tables[index] = cur->_next;
					else
						prev->_next = cur->_next;

					delete cur;
					//cur = nullptr;

					_dataNum--;
					return true;
				}
				else
				{
					prev = cur;
					cur = cur->_next;
				}
			}

			return false;
		}

		// 将key进行取模计算映射位置
		size_t HashFunc(const K& key, size_t size)
		{
			Hash hash; // 哈希仿函数将key转成整形
			return hash(key) % size;
		}

	private:
		vector<Node*> _tables;
		size_t   _dataNum = 0;
	};

	
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值