【C++】unordered_map_set 模拟实现

目录

[1. unordered_map_set 与 map_set 类的区别:](#1. unordered_map_set 与 map_set 类的区别:)

[1.1 hash 哈希底层 增删查改函数实现:](#1.1 hash 哈希底层 增删查改函数实现:)

[1.1.1 增 insert:](#1.1.1 增 insert:)

[1.1.2 删 erase:](#1.1.2 删 erase:)

[1.1.3 查 find:](#1.1.3 查 find:)

[1.1.4 改 operator\[\](map独有的):](#1.1.4 改 operator[](map独有的):)

[1.2 迭代器 iterator:](#1.2 迭代器 iterator:)

[1.2.1 hashIterator 结构体:](#1.2.1 hashIterator 结构体:)

[1.2.2 begin end :](#1.2.2 begin end :)

[1.2.3 operator++ :](#1.2.3 operator++ :)

[1.2.4 完善以及其他函数:](#1.2.4 完善以及其他函数:)

[1.3 hash 底层与 unodered_map_set 底层的适配:](#1.3 hash 底层与 unodered_map_set 底层的适配:)

[1.3.1 unordered_map:](#1.3.1 unordered_map:)

[1.3.2 unordered_set:](#1.3.2 unordered_set:)

[2. unordered_map_set 代码:](#2. unordered_map_set 代码:)


1. unordered_map_set 与 map_set 类的区别:

unordered_map_set 与 map_set 类的区别主要在于底层,普通的map_set 底层主要是以红黑树的底层代码实现的,而unordered_map_set 主要以哈希表实现的,准确来说哈希表的hashTables 来实现的。

unordered_map_set

  1. 平均增删查 O (1),数据量大的时候,单点查找、去重判断远快于 map/set
  2. 只做等值查询(有没有这个 key)场景性能强
  3. 接口和 map/set 几乎一致,上手成本低

缺点:遍历无序;哈希冲突、rehash 会退化到 O (n);内存开销更大;rehash 时迭代器全部失效;key 需要哈希函数 + == 判断

1.1 hash 哈希底层 增删查改函数实现:

1.1.1 增 insert:

增长就需要扩容 capacity():

优先待定扩容的相关数值,每一个数值都是质数,前一个质数都是后一个质数的两倍左右,第一个质数为11,哈希表的极限是在4亿左右,扩容就需要把之前的内容进行重新排列。

cpp 复制代码
			const size_t _capacity(const size_t size)
			{
				static const size_t size_count[] = {
				11,			23,			47,			97,			197,
				397,		797,		1597,		3203,		6421,
				12853,		25717,		51437,		102877,		205759,
				411527,		823117 ,	1646237 ,	3292489 ,	6584983 ,
				13169977 ,	26339969 ,	52679969 ,	105359939 ,	210719881 ,
				421439767 };
				size_t i = 0;
				while (i < 26)
				{
					if (size_count[i] > size)
					{
						return size_count[i];
					}
					i++;
				}
				return 0;
			}

			bool capacity(size_t size)
			{
				size = _capacity(size + 1);
				if (size == 0)
				{
					return false;
				}

				vector<T> old_table;
				for (Node* head : _tables)
				{
					for (Node* cur = head; cur != nullptr; cur = cur->_next)
					{
						old_table.push_back(cur->_data);
					}
				}
				clear();
				_tables.resize(size, nullptr);
				for (const T& data : old_table)
				{
					Insert(data);
				}
				return true;
			}

insert 增:

增加判断是否扩容 > 判断是否存在已有的内容 > 插入(一二步骤可以调换)

cpp 复制代码
			// 插入值为data的元素,如果data存在则不插入
			bool Insert(const T& data)
			{
				if (_n == _tables.size())
				{
					bool input = capacity(_tables.size());
					assert(input);
				}
				Hash hash;
				KeyOfT Key;
				bool find = Find(Key(data));
				if (find == true)
				{
					return false;
				}
				size_t hash0 = hash(Key(data)) % _tables.size();
				if (_tables[hash0] == nullptr)
				{
					_tables[hash0] = new Node(data);
					_n++;
					return true;
				}
				Node* next = _tables[hash0];
				while (next->_next != nullptr)
				{
					next = next->_next;
				}
				next->_next = new Node(data);
				_n++;
				return true;
			}

1.1.2 删 erase:

查找位置判断是否存在(查找过程中需要按时保留上一个点的位置确保不会野指针访问)

cpp 复制代码
			// 哈希桶中删除key的元素,删除成功返回true,否则返回false
			bool Erase(const K& key)
			{
				Hash hash;
				KeyOfT Key;
				size_t hash0 = hash(key) % _tables.size();
				Node* next = _tables[hash0], * last = nullptr;
				while (next != nullptr)
				{
					if (Key(next->_data) == key && next == _tables[hash0])
					{
						_tables[hash0] = next->_next;
						delete next;
						_n--;
						return true;
					}
					else if (Key(next->_data) == key)
					{
						last->_next = next->_next;
						delete next;
						_n--;
						return true;
					}
					else
					{
						last = next;
						next = next->_next;
					}
				}
				return false;
			}

1.1.3 查 find:

按哈希表的结构查找即可找到,若找不到说明不存在。

cpp 复制代码
			// 在哈希桶中查找值为key的元素,存在返回true否则返回false
			pair<Node*,bool> Find(const K& key)
			{
				Hash hash;
				KeyOfT Key;
				size_t hash0 = hash(key) % _tables.size();
				Node* find = _tables[hash0];
				while (find != nullptr)
				{
					if (Key(find->_data) == key)
					{
						return pair<Node*,bool>(find,true);
					}
					else
					{
						find = find->_next;
					}
				}
				return pair<Node*, bool>(nullptr,false);
			}

1.1.4 改 operator\[\](map独有的):

因为 map 存在 operator\[\] 运算符重载,就需要对 find insert 进行返回值的修改;需要放回两个类型,需要pair 的参数与。

cpp 复制代码
		V& operator[](const K& key)
		{
			auto insert = _map.Insert(const_data(key, V()));
			return insert.first->_data.second;
		}

insert 的函数修改:

cpp 复制代码
			// 插入值为data的元素,如果data存在则不插入
			pair<Node*,bool> Insert(const T& data)
			{
				if (_n == _tables.size())
				{
					bool input = capacity(_tables.size());
					assert(input);
				}
				Hash hash;
				KeyOfT Key;
				pair<Node*, bool> find = Find(Key(data));
				if (find.second == true)
				{
					return pair<Node*, bool>(find.first,false);
				}
				size_t hash0 = hash(Key(data)) % _tables.size();
				if (_tables[hash0] == nullptr)
				{
					_tables[hash0] = new Node(data);
					_n++;
					return pair<Node*, bool>(_tables[hash0],true);
				}
				Node* next = _tables[hash0];
				while (next->_next != nullptr)
				{
					next = next->_next;
				}
				next->_next = new Node(data);
				_n++;
				return pair<Node*, bool>(next->_next,true);
			}

find 函数修改:

cpp 复制代码
			// 在哈希桶中查找值为key的元素,存在返回true否则返回false
			pair<Node*,bool> Find(const K& key)
			{
				Hash hash;
				KeyOfT Key;
				size_t hash0 = hash(key) % _tables.size();
				Node* find = _tables[hash0];
				while (find != nullptr)
				{
					if (Key(find->_data) == key)
					{
						return pair<Node*,bool>(find,true);
					}
					else
					{
						find = find->_next;
					}
				}
				return pair<Node*, bool>(nullptr,false);
			}

1.2 迭代器 iterator:

哈希表的迭代器不能像 vector 那样用「指针 + 下标」直接遍历,因为哈希桶里的节点是分散挂在各个桶上的链表,桶与桶之间并不连续。因此需要单独封装一个迭代器结构体,内部同时记录当前节点指针 和所属哈希表指针,才能在遍历完一个桶后跳到下一个非空桶。

迭代器的核心职责有三个:一是像指针一样支持 *it、it->first 这样的解引用访问;二是通过 operator++ 实现「先走当前桶的链表,链表走完再向后寻找下一个非空桶」的跨桶移动;三是提供 begin() 与 end(),让 unordered_map/unordered_set 能够套用范围 for 等标准遍历写法。需要注意,rehash 之后所有迭代器都会失效,遍历过程中也不应插入或删除元素。

1.2.1 hashIterator 结构体:

  1. _node : 负责每一个节点上每一个延升出去的指针;
  2. _bucket: 主要负责的是每一个节点的指针;
  3. _end : 负责检查结束位置;
cpp 复制代码
		template<class T, class Ptr, class Ref>
		struct HashTableIterator
		{
			typedef HashTableIterator<T, Ptr, Ref> Self;
			typedef HashNode<T> Node;
			Node* _node;
			Node* const* _bucket;
			Node* const* _end;

			HashTableIterator(Node* node, Node* const* bucket, Node* const* end)
				:_node(node), _bucket(bucket), _end(end)
			{}
		};

1.2.2 begin end :

  1. begin():需要进行一定的查找的,不是每一个vector 第一个内容就是begin(),可能有空指针的情况,所以需要while 查找
  2. end ():相对来说就比较简单,直接就是最后一个位置,_node 的 位置还可以用nullptr 代替

注意: _bucket 和 _end 类型都是二级指针,_node 是一级指针

cpp 复制代码
			iterator end()
			{
				Node* const* last = _tables.data() + _tables.size();
				return iterator(nullptr, last, last);
			}
			iterator begin()
			{
				Node* const* cur = _tables.data();
				Node* const* last = cur + _tables.size();
				while (cur != last && *cur == nullptr)
				{
					++cur;
				}
				return iterator(cur == last ? nullptr : *cur, cur, last);
			}

const_iterator :

cpp 复制代码
			const_iterator end() const
			{
				Node* const* last = _tables.data() + _tables.size();
				return const_iterator(nullptr, last, last);
			}
			const_iterator begin() const
			{
				Node* const* cur = _tables.data();
				Node* const* last = cur + _tables.size();
				while (cur != last && *cur == nullptr)
				{
					++cur;
				}
				return const_iterator(cur == last ? nullptr : *cur, cur, last);
			}

1.2.3 operator++ :

每次++ ,_node = _node->next 运算完毕之后还需要进行判断是否已经到了空指针,_bucket 是否需要进行移动,_bucket 移动是否已经到了 _end 位置;

cpp 复制代码
			Self& operator++()
			{
				if (_node->_next != nullptr)
				{
					_node = _node->_next;
					return *this;
				}
				while (++_bucket != _end && *_bucket == nullptr)
				{
				}
				_node = (_bucket == _end) ? nullptr : *_bucket;
				return *this;
			}

1.2.4 完善以及其他函数:

cpp 复制代码
			Ptr operator->() const
			{
				return &_node->_data;
			}
			Ref operator*() const
			{
				return _node->_data;
			}
			bool operator==(const Self& it) const
			{
				return _node == it._node;
			}
			bool operator!=(const Self& it) const
			{
				return !(*this == it);
			}

1.3 hash 底层与 unodered_map_set 底层的适配:

1.3.1 unordered_map:

cpp 复制代码
	template <class K,class V>
	class unordered_map
	{

	public:
		typedef pair<K, V> data;
		typedef const pair<K, V> const_data;
		struct KeyMap
		{
			const K& operator()(const_data& kv)
			{
				return kv.first;
			}
		};
		typedef typename HashTable<K, data, KeyMap>::iterator iterator;
		typedef typename HashTable<K, data, KeyMap>::const_iterator const_iterator;
		// 构造
		unordered_map()
		{ }
		bool insert(const_data& kv)
		{
			auto ins = _map.Insert(kv);
			return ins.second;
		}
		bool erase(const K& key)
		{
			return _map.Erase(key);
		}
		bool find(const K& key)
		{
			auto find = _map.Find(key);
			return find.second;
		}
		V& operator[](const K& key)
		{
			auto insert = _map.Insert(const_data(key, V()));
			return insert.first->_data.second;
		}
		// 迭代器 iterator
		iterator begin() { return _map.begin(); }
		iterator end() { return _map.end(); }
		const_iterator begin() const { return _map.begin(); }
		const_iterator end() const { return _map.end(); }

	private:
		HashTable<K, data, KeyMap> _map;

	};

1.3.2 unordered_set:

cpp 复制代码
	template <class K>
	class unordered_set
	{
	public:
		struct KeySet
		{
			const K& operator()(const K& key)
			{
				return key;
			}
		};
		typedef typename HashTable<K, K, KeySet>::iterator iterator;
		typedef typename HashTable<K, K, KeySet>::const_iterator const_iterator;
		bool insert(const K& key)
		{
			auto insert = _set.Insert(key);
			return insert.second;
		}
		bool erase(const K& key)
		{
			return _set.Erase(key);
		}
		bool find(const K& key)
		{
			auto find = _set.Find(key);
			return find.second;
		}
		iterator begin() { return _set.begin(); }
		iterator end() { return _set.end(); }
		const_iterator begin() const { return _set.begin(); }
		const_iterator end() const { return _set.end(); }

	private:
		HashTable<K, K, KeySet> _set;
	};

2. unordered_map_set 代码:

unordered_map_set · 浪子·悠仁/C++ 知识库 - 码云 - 开源中国

相关推荐
Risehuxyc2 小时前
为什么php结束符?>省略不写
开发语言·php
kissskill2 小时前
MUDUO 学习笔记
c++·muduo
旖旎夜光3 小时前
【C 语言】(二)模拟实现 strlen、strcpy、strcmp、strstr、memcpy、memmove
c语言·开发语言·笔记·学习
codeejun4 小时前
每日一Go·MySQL-22、幻读、不可重复读、脏读实战演示
开发语言·mysql·golang
云草桑4 小时前
C#入坑JAVA 潜规则 API Get 多参数 Spring Boot与Spring Cloud 区别 入门系列4
java·开发语言
码途行者13 小时前
每天10分钟学Go:第17课 接口interface-只规定“能做什么“,不管它是什么
开发语言·后端·golang
头发还在的女程序员13 小时前
Java充电桩平台源码解析:枪口状态、上报时间与页面刷新怎样协同
java·开发语言·充电桩系统·充电桩管理·充电系统·充电小程序
timeDifference₇14 小时前
Python Vibe Coding实操实验报告
开发语言·jvm·python
geovindu15 小时前
python:DecisionTree
开发语言·后端·python·算法