C++Hash实现myunordered_map&set

文章目录

    • 一、框架分析
    • 二、模拟实现
      • iterator实现思路分析
    • 三、代码实现
    • 四、总结

一、框架分析

GI-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
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
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
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的是pair
需要注意的是源码里面跟map/set源码类似,命名风格比较乱,这里比map和set还乱,hash_set模板参数居然用的Value命名,hash_map用的是Key和T命名,可见大佬有时写代码也不规范,乱弹琴。下面模拟⼀份自己的出来,就按自己的风格走了。

二、模拟实现

实现出复用哈希表的框架,并支持insert
参考源码框架,unordered_map和unordered_set复用之前我们实现的哈希表。

  • 这里相比源码调整⼀下,key参数就用K,value参数就用V,哈希表中的数据类型,使用T。
  • 其次跟map和set相比而言unordered_map和unordered_set的模拟实现类结构更复杂⼀点,但是大框架和思路是完全类似的。因为HashTable实现了泛型不知道T参数导致是K,还是pair,那么insert内部进行插入时要用K对象转换成整形取模和K比较相等,因为pair的value不参与计算取模,且默认支持的是key和value⼀起比较相等,我们需要时的任何时候只需要比较K对象,所以我们在unordered_map和unordered_set层分别实现⼀个MapKeyOfT和SetKeyOfT的仿函数传给HashTable的KeyOfT,然后HashTable中通过KeyOfT仿函数取出T类型对象中的K对象,再转换成整形取模和K比较相等,具体细节参考如下代码实现。
// MyUnorderedSet.h
namespace bit
{
	template<class K, class Hash = HashFunc<K>>
	class unordered_set
	{
		struct SetKeyOfT
		{
			const K& operator()(const K& key)
			{
				return key;
			}
		};
	public:
		bool insert(const K& key)
		{
			return _ht.Insert(key);
		}
	private:
		hash_bucket::HashTable<K, K, SetKeyOfT, Hash> _ht;
	};
}

// MyUnorderedMap.h
namespace bit
{
	template<class K, class V, class Hash = HashFunc<K>>
	class unordered_map
	{
		struct MapKeyOfT
		{
			const K& operator()(const pair<K, V>& kv)
			{
				return kv.first;
			}
		};
	public:
		bool insert(const pair<K, V>& kv)
		{
			return _ht.Insert(kv);
		}
	private:
		hash_bucket::HashTable<K, pair<K, V>, MapKeyOfT, Hash> _ht;
	};
}

iterator实现思路分析

  • iterator实现的大框架跟list的iterator思路是⼀致的,用⼀个类型封装结点的指针,再通过重载运算符实现,迭代器像指针⼀样访问的行为,要注意的是哈希表的迭代器是单向迭代器。
  • 这里的难点是operator++的实现。iterator中有⼀个指向结点的指针,如果当前桶下面还有结点,则结点的指针指向下⼀个结点即可。如果当前桶走完了,则需要想办法计算找到下⼀个桶。这⾥的难点是反而是结构设计的问题,参考上面的源码,我们可以看到iterator中除了有结点的指针,还有哈希表对象的指针,这样当前桶走完了,要计算下⼀个桶就相对容易多了,用key值计算出当前桶位置,依次往后找下⼀个不为空的桶即可。
  • begin()返回第⼀个桶中第⼀个节点指针构造的迭代器,这里end()返回迭代器可以用空表示。
  • unordered_set的iterator也不⽀持修改,我们把unordered_set的第⼆个模板参数改成constK即可, HashTable _ht;
  • unordered_map的iterator不支持修改key但是可以修改value,我们把unordered_map的第⼆个
    模板参数pair的第⼀个参数改成const K即可, HashTable, MapKeyOfT, Hash> _ht;
  • 支持完整的迭代器还有很多细节需要修改,具体参考下面的代码。
    C++Hash实现myunordered_map&set_第1张图片

map支持[]
unordered_map要支持[]主要需要修改insert返回值支持,修改HashTable中的insert返回值为
pair Insert(const T& data)
有了insert支持[]实现就很简单了,具体参考下面代码实现

三、代码实现

MyUnorderedSet.h

namespace tu
{
	template<class K, class Hash = HashFunc<K>>
	class unordered_set
	{
		struct SetKeyOfT
		{
			const K& operator()(const K& key)
			{
				return key;
			}
		};
	public:
		typedef typename hash_bucket::HashTable<K, const K, SetKeyOfT,
			Hash>::Iterator iterator;
		typedef typename hash_bucket::HashTable<K, const K, SetKeyOfT,
			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);
		}

		iterator Find(const K & key)
		{
			return _ht.Find(key);
		}

		bool Erase(const K & key)
		{
			return _ht.Erase(key);
		}

	private:
		hash_bucket::HashTable<K, const K, SetKeyOfT, Hash> _ht;
	};
	void test_set()
	{
		unordered_set<int> s;
		int a[] = { 4, 2, 6, 1, 3, 5, 15, 7, 16, 14, 3,3,15 };
		for (auto e : a)
		{
			s.insert(e);
		}

		for (auto e : s)
		{
			cout << e << " ";
		}
		cout << endl;
		unordered_set<int>::iterator it = s.begin();
		while (it != s.end())
		{
			// 不支持修改 
			//*it += 1;

			cout << *it << " ";
			++it;
		}
		cout << endl;
	}
}

MyUnorderedMap.h

namespace tu
{
	template<class K, class V, class Hash = HashFunc<K>>
	class unordered_map
	{
		struct MapKeyOfT
		{
			const K& operator()(const pair<K, V>& kv)
			{
				return kv.first;
			}
		};
	public:
		typedef typename hash_bucket::HashTable<K, pair<const K, V>,
			MapKeyOfT, Hash>::Iterator iterator;
		typedef typename hash_bucket::HashTable<K, pair<const K, V>,
			MapKeyOfT, 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);
		}
		V& operator[](const K& key)
		{
			pair<iterator, bool> ret = _ht.Insert(make_pair(key, V()));
			return ret.first->second;
		}
		iterator Find(const K& key)
		{
			return _ht.Find(key);
		}
		bool Erase(const K& key)
		{
			return _ht.Erase(key);
		}
	private:
		hash_bucket::HashTable<K, pair<const K, V>, MapKeyOfT, Hash> _ht;
	};
	void test_map()
	{
		unordered_map<string, string> dict;
		dict.insert({ "sort", "排序" });
		dict.insert({ "left", "左边" });
		dict.insert({ "right", "右边" });
		dict["left"] = "左边,剩余";
		dict["insert"] = "插⼊";
		dict["string"];
		unordered_map<string, string>::iterator it = dict.begin();
		while (it != dict.end())
		{
			// 不能修改first,可以修改second 
			//it->first += 'x';
			it->second += 'x';
			cout << it->first << ":" << it->second << endl;
			++it;
		}
		cout << endl;
	}
}

HashTable.h

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 *= 131;
			hash += e;
		}
		return hash;
	}
};
namespace hash_bucket
{
	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 HashTable;
	template<class K, class T, class Ptr, class Ref, class KeyOfT, class Hash>
	struct HTIterator
	{
		typedef HashNode<T> Node;
		typedef HTIterator<K, T, Ptr, Ref, KeyOfT, Hash> Self;
		Node* _node;
		const HashTable<K, T, KeyOfT, Hash>* _pht;
		HTIterator(Node* node, const HashTable<K, T, KeyOfT, Hash>* pht)
			:_node(node)
			, _pht(pht)
		{}
		Ref operator*()
		{
			return _node->_data;
		}
		Ptr operator->()
		{
			return &_node->_data;
		}
		bool operator!=(const Self& s)
		{
			return _node != s._node;
		}
		Self& operator++()
		{
			if (_node->_next)
			{
				// 当前桶还有节点 
				_node = _node->_next;
			}
			else
			{
				// 当前桶⾛完了,找下⼀个不为空的桶 
				KeyOfT kot;
				Hash hs;
				size_t hashi = hs(kot(_node->_data)) % _pht -> _tables.size();
				++hashi;
				while (hashi < _pht->_tables.size())
				{
					if (_pht->_tables[hashi])
					{
						break;
					}
					++hashi;
				}
				if (hashi == _pht->_tables.size())
				{
					_node = nullptr; // end()
				}
				else
				{
					_node = _pht->_tables[hashi];
				}
			}
			return *this;
		}
	};
	template<class K, class T, class KeyOfT, class Hash>
	class HashTable
	{
		// 友元声明 
		template<class K, class T, class Ptr, class Ref, class KeyOfT, class
			Hash>
		friend struct HTIterator;
		typedef HashNode<T> Node;
	public:
		typedef HTIterator<K, T, T*, T&, KeyOfT, Hash> Iterator;
		typedef HTIterator<K, T, const T*, const T&, KeyOfT, Hash>
			ConstIterator;
		Iterator Begin()
		{
			if (_n == 0)
				return End();
			for (size_t i = 0; i < _tables.size(); i++)
			{
				Node* cur = _tables[i];
				if (cur)
				{
					return Iterator(cur, this);
				}
			}
			return End();
		}
		Iterator End()
		{
			return Iterator(nullptr, this);
		}
		ConstIterator Begin() const
		{
			if (_n == 0)
				return End();
			for (size_t i = 0; i < _tables.size(); i++)
			{
				Node* cur = _tables[i];
				if (cur)
				{
					return ConstIterator(cur, this);
				}
			}
			return End();
		}
		ConstIterator End() const
		{
			return ConstIterator(nullptr, this);
		}
		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
			};
			const unsigned long* first = __stl_prime_list;
			const unsigned long* last = __stl_prime_list +
				__stl_num_primes;
			const unsigned long* pos = lower_bound(first, last, n);
			return pos == last ? *(last - 1) : *pos;
		}
		HashTable()
		{
			_tables.resize(__stl_next_prime(_tables.size()), nullptr);
		}
		~HashTable()
		{
			// 依次把每个桶释放 
			for (size_t i = 0; i < _tables.size(); i++)
			{
				Node* cur = _tables[i];
				while (cur)
				{
					Node* next = cur->_next;
					delete cur;
					cur = next;
				}
				_tables[i] = nullptr;
			}
		}
		pair<Iterator, bool> Insert(const T& data)
		{
			KeyOfT kot;
			Iterator it = Find(kot(data));
			if (it != End())
				return make_pair(it, false);
			Hash hs;
			size_t hashi = hs(kot(data)) % _tables.size();
			// 负载因⼦==1扩容 
			if (_n == _tables.size())
			{
				vector<Node*>
					newtables(__stl_next_prime(_tables.size()), nullptr);
				for (size_t i = 0; i < _tables.size(); i++)
				{
					Node* cur = _tables[i];
					while (cur)
					{
						Node* next = cur->_next;
						// 旧表中节点,挪动新表重新映射的位置 
						size_t hashi = hs(kot(cur->_data)) %
							newtables.size();
						// 头插到新表 
						cur->_next = newtables[hashi];
						newtables[hashi] = cur;

						cur = next;
					}
					_tables[i] = nullptr;
				}
				_tables.swap(newtables);
			}
			// 头插 
			Node* newnode = new Node(data);
			newnode->_next = _tables[hashi];
			_tables[hashi] = newnode;
			++_n;
			return make_pair(Iterator(newnode, this), true);
		}
		Iterator Find(const K& key)
		{
			KeyOfT kot;
			Hash hs;
			size_t hashi = hs(key) % _tables.size();
			Node* cur = _tables[hashi];
			while (cur)
			{
				if (kot(cur->_data) == key)
				{
					return Iterator(cur, this);
				}
				cur = cur->_next;
			}
			return End();
		}
		bool Erase(const K& key)
		{
			KeyOfT kot;
			Hash hs;
			size_t hashi = hs(key) % _tables.size();
			Node* prev = nullptr;
			Node* cur = _tables[hashi];
			while (cur)
			{
				if (kot(cur->_data) == key)
				{
					if (prev == nullptr)
					{
						_tables[hashi] = cur->_next;
					}
					else
					{
						prev->_next = cur->_next;
					}
					delete cur;
					--_n;
					return true;
				}
				prev = cur;
				cur = cur->_next;
			}
			return false;
		}
 private:
	 vector<Node*> _tables; // 指针数组 
	 size_t _n = 0; // 表中存储数据个数 
 };
}

四、总结

在C++中实现自定义的myunordered_mapmyunordered_set时,核心在于仿照标准库的哈希容器设计,围绕哈希表的数据结构展开。两者的底层均依赖动态数组(桶数组)与链表(或红黑树)结合的方式管理元素,通过哈希函数将键映射到桶索引,利用链地址法处理冲突。对于myunordered_map,每个节点需存储键值对pair,而myunordered_set仅需存储键值Key,因此模板参数需分别适配:map需定义键(Key)、值类型(T)、哈希函数(Hash)和键相等比较(KeyEqual),set则省略值类型。哈希函数需支持默认特化(如std::hash)和用户自定义扩展,键相等比较通常通过operator==或自定义仿函数实现。

桶数组的初始容量通常设为质数以减少哈希聚集,动态扩容通过负载因子(如默认0.75)触发,当元素数超过负载因子×桶数时,桶数组扩容至约两倍大小并重新哈希分布元素,此过程需遍历原哈希表所有节点并重新插入新桶,确保均摊时间复杂度为O(1)。迭代器的实现需跨桶遍历,内部需记录当前桶索引及链表节点指针,++操作时若当前链表遍历完毕,则跳至下一个非空桶继续。对于myunordered_map,需重载operator[]以支持类似map[key] = value的语法,其底层通过insertfind实现,若键不存在则插入默认值。

内存管理需手动分配节点内存,插入时创建新节点并挂载到对应桶链表头部,删除时需正确处理链表指针以避免断裂。与STL的差异点包括:标准库可能采用单向链表(如std::forward_list)优化内存,而自定义实现为简化可用双向链表;此外,STL在C++11后通过unordered_map::reserve预分配桶以减少扩容开销,自定义实现可类似支持。性能优化可引入桶内红黑树(当链表长度超过阈值时)以应对极端哈希冲突,但复杂度陡增。需注意哈希函数的质量,若分布不均会导致桶链表过长,退化为O(n)查找。最后,需通过单元测试覆盖边界条件(如空容器、全冲突场景、迭代器失效规则等),确保行为与标准库一致。
ps:数据结构~哈希的学习

你可能感兴趣的:(C++,哈希算法,c++,算法)