【C++哈希应用】模拟实现STL中的unordered_map和unordered_set

news2024/9/23 15:27:11

目录

  • 🚀 前言
  • 一: 🔥 哈希表的改造
    • 1.1 模板参数列表的改造
    • 1.2 增加迭代器操作
  • 二: 🔥 封装unordered_map和unordered_set
    • 2.1 unordered_map的模拟实现:
      • 2.1.1 unordered_map的测试
    • 2.2 unordered_set的模拟实现
      • 2.2.1 unordered_set的测试
  • 三: 🔥 📖哈希表改造的完整代码及总结

🚀 前言

哈希类的实现参考上一篇文章:【C++高阶】哈希:全面剖析与深度学习

前面我们对哈希表进行了介绍并用哈希桶进行了实现!本期我们在上期的基础上对哈希表进行改造,并封装出unordered_map和unordered_set!本篇我们采用开散列的方式来模拟实现unordered

————————————步骤—————————————
1. 实现哈希表
2. 实现 iterator 迭代器
3. 封装unordered_map和unordered_set 解决KetOfT
4. 实现 const_iterator 迭代器
5. 修改Key的问题
6. 解决operate[]

一: 🔥 哈希表的改造

1.1 模板参数列表的改造

// K: 关键码类型
// V: 不同容器V的类型不同,如果是unordered_map,V代表一个键值对,如果是 unordered_set,V 为 K
// KeyOfValue: 因为V的类型不同,通过 value 取 key 的方式就不同,详细见unordered_map/set的实现
// HF: 哈希函数仿函数对象类型,哈希函数使用除留余数法,需要将Key转换为整形数字才能取模
template<class K, class V, class KeyOfValue, class HF = DefHashF<T> >
class HashBucket;

1.2 增加迭代器操作

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

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

// 为了实现简单,在哈希桶的迭代器类中需要用到hashBucket本身,所以我们要进行一下前置声明,并且我们在 HashTable 中也要设置一个友元(friend)
 
//前置声明
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;                                                          // 注意这里必须要++hashi 调试了好久 因为如果不++ 旧的桶遍历完了会一直重复遍历死循环 当_node->next为空时必须++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;
	}
};

二: 🔥 封装unordered_map和unordered_set

2.1 unordered_map的模拟实现:

#pragma once

#include "HashTable.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:
		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;
	};
}

2.1.1 unordered_map的测试

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;
}

2.2 unordered_set的模拟实现

#pragma once

#include "HashTable.h"

namespace bit
{
	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;             // set不允许修改key 所以+const
	};

	void Print(const unordered_set<int>& s)
	{
		unordered_set<int>::const_iterator it = s.begin();
		while (it != s.end())
		{
			cout << *it << " ";
			++it;
		}
		cout << endl;
	}

	struct Date
	{
		int _year;
		int _month;
		int _day;

		bool operator==(const Date& d) const
		{
			return _year == d._year && _month == d._month && _day == d._day;
		}
	};
	//  针对date类型专门设计的哈希函数
	struct HashDate
	{
		size_t operator()(const Date& key) 
		{
			return (key._year * 31 + key._month) * 31 + key._day;
		}
	};
}

在这里插入图片描述

2.2.1 unordered_set的测试

void Print(const unordered_set<int>& s)
{
	unordered_set<int>::const_iterator it = s.begin();
	while (it != s.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;
}

struct Date
{
	int _year;
	int _month;
	int _day;

	bool operator==(const Date& d) const
	{
		return _year == d._year && _month == d._month && _day == d._day;
	}
};
//  针对date类型专门设计的哈希函数
struct HashDate
{
	size_t operator()(const Date& key) 
	{
		return (key._year * 31 + key._month) * 31 + key._day;
	}
};

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())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;

	unordered_set<Date, HashDate> us;

	us.insert({ 2023, 1, 1 });
	us.insert({ 2024, 1, 1 });

	Print(s);
}

在这里插入图片描述

三: 🔥 📖哈希表改造的完整代码及总结

#pragma once

#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <map>

using namespace std;

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 *= 31;
			hash += e;
		}

		return hash;
	}
};


enum State
{
	EXIST,
	EMPTY,
	DELETE
};

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;                                                          // 注意这里必须要++hashi 调试了好久 因为如果不++ 旧的桶遍历完了会一直重复遍历死循环 当_node->next为空时必须++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);                // 太妙了, 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);                // 太妙了, this就是哈希表对象的指针
				}
			}

			return End();
		}

		ConstIterator End() const
		{
			return ConstIterator(nullptr, this);
		}

		HashTable()
		{
			_tables.resize(10, 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 (Find(kot(data)) != End())
				return make_pair(it, false);

			Hash hs;
			size_t hashi = hs(kot(data)) % _tables.size();

			// 负载因子==1扩容
			if (_n == _tables.size())
			{
				/*HashTable<K, V> newHT;
				newHT._tables.resize(_tables.size() * 2);
				for (size_t i = 0; i < _tables.size(); i++)
				{
					Node* cur = _tables[i];
					while (cur)
					{
						newHT.Insert(cur->_kv);
						cur = cur->_next;
					}
				}

				_tables.swap(newHT._tables);*/

				vector<Node*> newtables(_tables.size() * 2, 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;                    // 存储数据的个数
	};    

}

以上就是本文的全部内容,需要我们好好掌握,觉得这篇博客对你有帮助的,可以点赞收藏关注支持一波~😉
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1964264.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

图像自定义画框box标注,坐标像素点获取;通过坐标点画框

1、jupyter-bbox-widget画框&#xff0c;这只能jupyter环境插件使用 pip install jupyter_bbox_widget ##安装 ##注册 jupyter nbextension enable --py --sys-prefix jupyter_bbox_widget使用 from jupyter_bbox_widget import BBoxWidget widget BBoxWidget(imagefruit.jp…

【深度学习】kaggle使用

https://blog.csdn.net/2301_78630677/article/details/133834096 https://blog.csdn.net/xiaojia1001/article/details/139467176 https://www.kaggle.com/ 使用要挂代理&#xff0c;要不然可能无法注册 绑定手机号之后才能使用GPU 每周30h免费GPU使用时长 上传数据集 Ad…

【文件解析漏洞】

使用windows2003sever服务器 第一个&#xff1a;目录解析 1、打开网站目录&#xff0c;右键打开资源管理器 新建一个1.asp文件 在1.asp目录下新建一个2.txt&#xff0c;输入asp的语句 2、使用本机访问windows2003的IP地址 访问http://192.168.189.155/1.asp/2.txt即可 第…

Minio多主机分布式 docker-compose 集群部署

参考 docker-compose搭建多主机分布式minio - 会bk的鱼 - 博客园 (cnblogs.com) 【运维】docker-compose安装minio集群-CSDN博客 Minio 是个基于 Golang 编写的开源对象存储套件&#xff0c;虽然轻量&#xff0c;却拥有着不错的性能 中文地址&#xff1a;MinIO | 用于AI的S3 …

CDP问卷调查

在数字化时代&#xff0c;CDP&#xff08;Customer Data Platform&#xff0c;客户数据平台&#xff09;作为连接企业与客户数据的关键桥梁&#xff0c;正逐渐成为企业营销策略中不可或缺的一环。为了更深入地理解CDP在企业中的应用现状、挑战与未来趋势&#xff0c;我们精心设…

A股探底强势反攻,量价齐声太漂亮

今天的A股探底回升&#xff0c;太阳线反攻&#xff0c;太漂亮了&#xff01;具体原因是这样的&#xff0c;盘面上出现2个重要变化&#xff0c;一起来看看&#xff1a; 1、今天两市低开高走&#xff0c;证券、人形机器人等板块掀起涨停潮&#xff0c;究竟是昙花一现还是有望迎来…

VMware虚拟机安装及虚拟机下安装ubuntu(附安装包)

VMware虚拟机安装及虚拟机下安装ubuntu 0 前期准备1 VMware安装2 VMware虚拟机下安装ubuntu2.1 配置虚拟机2.2 安装虚拟机ubuntu 3 在虚拟机中卸载Ubuntu参考 0 前期准备 1、VMware Wworkstation Pro安装包下载 官网-添加链接描述 百度网盘分享&#xff1a; 链接: VMware 提取…

【ThingsBoard初体验】本地编译踩坑记录

前言 这只是我自己的踩坑记录&#xff0c;以尽快启动项目为主&#xff0c;暂时不对编译出现的问题做深入分析。 第一次接触物联网项目&#xff0c;对于文章出现的问题&#xff0c;如果能帮到其他小伙伴&#xff0c;那是我的荣幸。 大佬们有更好的解决办法&#xff0c;也希望能够…

TypeError: Components is not a function

Vue中按需引入Element-plus时&#xff0c;报错TypeError: Components is not a function。 1、参考Element-plus官方文档 安装unplugin-vue-components 和 unplugin-auto-import这两款插件 2、然后需要在vue.config.js中配置webPack打包plugin配置 3、重新启动项目会报错 T…

消息中间件分享

消息中间件分享 1 为什么使用消息队列2 消息队列有什么缺点3 如何保证消息队列的高可用4 如何处理消息丢失的问题?5 如何保证消息的顺序性1 为什么使用消息队列 解耦、异步、削峰 解耦 不使用中间件的场景 使用中间件的场景 异步 不使用中间件 使用中间件 削峰 不使…

【redis】redis高可用 哨兵模式 一主二从三哨兵部署教程

哨兵模式&#xff1a;自动主从同步、自动选举主节点&#xff1b;基本可以满足大部分业务场景&#xff1b; 在针对大规模数据和高并发请求的场景、数据不能丢失&#xff0c;才需要用到集群模式。 本文教程基于redis3 , centos 8 stream操作系统&#xff0c;理论上来说 redis3也好…

利用 Python 制作图片轮播应用

在这篇博客中&#xff0c;我将向大家展示如何使用 xPython 创建一个图片轮播应用。这个应用能够从指定文件夹中加载图片&#xff0c;定时轮播&#xff0c;并提供按钮来保存当前图片到收藏夹或仅轮播收藏夹中的图片。我们还将实现退出按钮和全屏显示的功能。 C:\pythoncode\new\…

http协议深度解析——网络时代的安全与效率(1)

作者简介&#xff1a;一名云计算网络运维人员、每天分享网络与运维的技术与干货。 公众号&#xff1a;网络豆云计算学堂 座右铭&#xff1a;低头赶路&#xff0c;敬事如仪 个人主页&#xff1a; 网络豆的主页​​​​​ 目录 写在前面&#xff1a; 本章目的&#xff1a; …

【Python学习手册(第四版)】学习笔记11.1-赋值语句(分解赋值、序列赋值、解包等)及变量命名规则详解

个人总结难免疏漏&#xff0c;请多包涵。更多内容请查看原文。本文以及学习笔记系列仅用于个人学习、研究交流。 本文主要对赋值语句的各种形式做详解&#xff0c;以非常通俗易懂的语言、循序渐进的方式&#xff0c;分别对单个、元组及列表分解、序列赋值、序列解包、多重目标…

LinuxCentos中ELK日志分析系统的部署(详细教程8K字)附图片

&#x1f3e1;作者主页&#xff1a;点击&#xff01; &#x1f427;Linux基础知识(初学)&#xff1a;点击&#xff01; &#x1f427;Linux高级管理防护和群集专栏&#xff1a;点击&#xff01; &#x1f510;Linux中firewalld防火墙&#xff1a;点击&#xff01; ⏰️创作…

Android发布Library至mavenCentral遇到 Received status code 401

一、由于我的AppUpdate 库最新的版本还是去年发布的&#xff0c;所以想着发布一个版本&#xff0c;可没想到什么都没有改动的情况下竟然返回401&#xff1b;检查了半天发现用户名和密码也没有错&#xff0c;百思不得解&#xff01; 二、最后没想到竟然是sonatype那边改了&#…

常见的Markdown编辑器推荐!

工欲善其事&#xff0c;必先利其器。一款好用的 Markdown 编辑器能极大地提高我们的写作体验&#xff0c;本篇博客就来介绍一些好用的编辑器。 ‍ ‍ Markdown 编辑器的分类 根据 Markdown 编辑器的使用环境&#xff0c;可以简单分为四类&#xff1a; 在线编辑器&#xff…

类和对象(中 )C++

默认成员函数就是用户不显示实现&#xff0c;编译器会自动实现的成员函数叫做默认成员函数。一个类&#xff0c;我们在不写的情况下&#xff0c;编译器会自动实现6个默认成员函数&#xff0c;需要注意&#xff0c;最重要的是前4个&#xff0c;其次就是C11以后还会增加两个默认成…

SpringBoot 优雅实现超大文件上传

​ 博客主页: 南来_北往 系列专栏&#xff1a;Spring Boot实战 前言 文件上传是一个老生常谈的话题了&#xff0c;在文件相对比较小的情况下&#xff0c;可以直接把文件转化为字节流上传到服务器&#xff0c;但在文件比较大的情况下&#xff0c;用普通的方式进行上传&…

hadoop学习笔记2-hdfs

3.HDFS 3.1HDFS两类节点 namenode&#xff1a;名称节点datanode&#xff1a;数据节点 1.namenode 1&#xff09;namenode用来存储元数据&#xff0c;接收客户端的读写请求&#xff0c;namenode的元数据会分别保存在磁盘和内存中&#xff0c;保存到内存是为了快速查询数据信…