C++利用开散列哈希表封装unordered_set,unordered_map

news2024/9/24 15:16:15

C++利用开散列哈希表封装unordered_set,unordered_map

  • 一.前言
    • 1.开散列的哈希表完整代码
  • 二.模板参数
    • 1.HashNode的改造
    • 2.封装unordered_set和unordered_map的第一步
      • 1.unordered_set
      • 2.unordered_map
    • 3.HashTable
  • 三.string的哈希函数的模板特化
  • 四.迭代器类
    • 1.operator++运算符重载
      • 1.动图演示+分析
      • 2.需要哈希表的地址,怎么办?
        • 1.解决双向依赖问题
        • 2.解决私有成员问题
    • 2.const迭代器的问题
    • 3.迭代器类的定义
    • 4.迭代器类的完善
      • 1.解引用和== !=
        • 1.解引用
        • 2.== !=
      • 2.operator++
      • 3.迭代器类的完整代码
  • 五.哈希表的修改
    • 1.begin和end
    • 2.insert
    • 3.find
    • 4.哈希表的完整代码
  • 六.unordered_set的完整代码
  • 七.unordered_map的完整代码
  • 八.test.cpp

一.前言

1.之前我们已经实现了开散列的哈希表,今天我们来用它封装unordered_set,unordered_map
2.本文的封装比利用红黑树封装set和map更加复杂
建议大家先去看我的红黑树封装set和map再来看本文
因为有很多地方跟红黑树封装set和map时是同样的思路和方法,所以本文不会太去赘述一遍

1.开散列的哈希表完整代码

namespace hash_bucket
{
	//HashFunc<int>
	template<class K>
	//整型的哈希函数
	struct HashFunc
	{
		size_t operator()(const K& key)
		{
			return (size_t)key;
		}
	};

	//HashFunc<string>
	//string的哈希函数
	template<>
	struct HashFunc<string>
	{
		size_t operator()(const string& key)
		{
			// BKDR
			size_t hash = 0;
			for (auto e : key)
			{
				hash *= 131;
				hash += e;
			}
			return hash;
		}
	};

	template<class K, class V>
	struct HashNode
	{
		HashNode* _next;
		pair<K, V> _kv;

		HashNode(const pair<K, V>& kv)
			:_kv(kv)
			, _next(nullptr)
		{}
	};

	template<class K, class V, class Hash = HashFunc<K>>
	class HashTable
	{
		typedef HashNode<K, V> Node;
	public:
		HashTable()
		{
			_tables.resize(10);
		}

		~HashTable()
		{
			for (int i = 0; i < _tables.size(); i++)
			{
				Node* cur = _tables[i];
				while (cur)
				{
					Node* next = cur->_next;
					delete cur;
					cur = next;
				}
				_tables[i] = nullptr;
			}
		}

		bool Insert(const pair<K, V>& kv)
		{
			//先查找在不在
			//如果在,返回false,插入失败
			if (Find(kv.first))
			{
				return false;
			}
			//扩容
			if (_n == _tables.size())
			{
				//开辟新的哈希表
				HashTable newtable;
				int newcapacity = _tables.size() * 2;
				//扩2倍
				newtable._tables.resize(newcapacity);
				//转移数据
				for (int i = 0; i < _tables.size(); i++)
				{
					Node* cur = _tables[i];
					while (cur)
					{
						Node* next = cur->_next;
						int hashi = hash(cur->_kv.first) % newtable._tables.size();
						cur->_next = newtable._tables[hashi];
						newtable._tables[hashi] = cur;
						cur = next;
					}
					//防止出现野指针导致重复析构...
					_tables[i] = nullptr;
				}
				//交换两个vector,从而做到交换两个哈希表
				//通过学习vector的模拟实现,我们知道vector进行交换时只交换first,finish,end_of_storage
				_tables.swap(newtable._tables);
			}
			//1.利用哈希函数计算需要插入到那个桶里面
			int hashi = hash(kv.first) % _tables.size();
			//头插
			Node* newnode = new Node(kv);
			newnode->_next = _tables[hashi];
			_tables[hashi] = newnode;
			++_n;
			return true;
		}

		Node* Find(const K& key)
		{
			int hashi = hash(key) % _tables.size();
			Node* cur = _tables[hashi];
			while (cur)
			{
				if (cur->_kv.first == key)
				{
					return cur;
				}
				cur = cur->_next;
			}
			return nullptr;
		}

		bool Erase(const K& key)
		{
			int hashi = hash(key) % _tables.size();
			Node* cur = _tables[hashi], * prev = nullptr;
			while (cur)
			{
				if (cur->_kv.first == key)
				{
					if (cur == _tables[hashi])
					{
						_tables[hashi] = cur->_next;
					}
					else
					{
						prev->_next = cur->_next;
					}
					return true;
				}
				prev = cur;
				cur = cur->_next;
			}
			return false;
		}

	private:
		//哈希表是一个指针数组
		vector<Node*> _tables;
		size_t _n = 0;
		Hash hash;
	};
}

二.模板参数

1.HashNode的改造

因为unordered_set是Key模型的容器
unordered_map是Key-Value模型的容器,所以需要对节点结构体进行改造

template<class V>
struct HashNode
{
	HashNode* _next;
	V _kv;

	HashNode(const V& kv)
		:_kv(kv)
		, _next(nullptr)
	{}
};

2.封装unordered_set和unordered_map的第一步

1.对于模板参数V:
如果是unordered_set:传入底层哈希表的就是Key,Key
如果是unordered_map:传入底层哈希表的就是Key,pair<const Key,Value>

2.为了取出关键字Key,需要传入仿函数
如果是unordered_set:仿函数返回Key
如果是unordered_map:仿函数返回pair<const Key,Value>的first

3.哈希函数需要传给unordered_set和unordered_map
由unordered_set和unordered_map传给底层的哈希表

1.unordered_set

namespace hash_bucket
{
	template<class K ,class Hash = HashFunc<K>>
	class unordered_set
	{
		struct SetofKey
		{
			const K& operator()(const K& k)
			{
				return k;
			}
		};
	private:
		HashTable<K, K,SetofKey,Hash> _ht;
	};
}

2.unordered_map

namespace hash_bucket
{
	template<class K,class V, class Hash = HashFunc<K>>
	class unordered_map
	{
		struct MapofKey
		{
			const K& operator()(const pair<const K, V>& k)
			{
				return k.first;
			}
		};
	private:
		HashTable<K, pair<const K, V>, MapofKey,Hash> _ht;
	};
}

3.HashTable

哈希表增加模板参数
1.K:就是关键字

2.V:就是具体存放的数据类型(unordered_set就是Key , unordered_map就是pair<const Key,Value>)

3.KeyofT:不同容器传入的取出其关键字的仿函数

如果是unordered_set:仿函数返回Key
如果是unordered_map:仿函数返回pair<const Key,Value>的first

4.Hash:仿函数,哈希函数,用于计算下标的

template<class K, class V,class KeyofT, class Hash>
class HashTable
{
......
private:
	//哈希表是一个指针数组
	vector<Node*> _tables;
	size_t _n = 0;
	Hash hash;//哈希函数的仿函数对象
	KeyofT _kot;//KeyofT的仿函数对象
};

三.string的哈希函数的模板特化

因为string类型的哈希映射太常用了,
所以这里使用了模板特化,以免每次要存放string时都要指名传入string的哈希函数

//HashFunc<int>
template<class K>
//整型的哈希函数
struct HashFunc
{
	size_t operator()(const K& key)
	{
		return (size_t)key;
	}
};

//HashFunc<string>
//string的哈希函数
template<>
struct HashFunc<string>
{
	size_t operator()(const string& key)
	{
		// BKDR
		size_t hash = 0;
		for (auto e : key)
		{
			hash *= 131;
			hash += e;
		}
		return hash;
	}
};

四.迭代器类

1.这里的哈希表只支持正向迭代器,不支持反向迭代器

1.operator++运算符重载

1.动图演示+分析

++有2种情况:

1.如果当前节点所在的当前哈希桶的后面还有节点,那么直接走到next节点即可
在这里插入图片描述
如果当前节点所在的当前哈希桶的后面没有节点了,那么就要走到下一个不为空的哈希桶才可以
在这里插入图片描述
如果后面没有不为空的哈希桶了,返回nullptr
在这里插入图片描述

2.需要哈希表的地址,怎么办?

我们可以在迭代器里面加入一个哈希表的指针,要求你给我传入你这个哈希表的地址,让我找到你这个哈希表(其实也可以加入一个vector<Node*>的指针,这样就不用传入哈希表指针了,这里以传入哈希表指针来演示,为了介绍如何解决双向依赖问题和友元声明问题)

同时也可以加入一个_hashi代表当前迭代器位于哈希表当中的下标

不过我们发现:
此时出现了一种鸡生蛋,蛋生鸡的双向依赖问题了
我们的迭代器有一个成员:哈希表的指针
哈希表有一个typedef后的类型:迭代器

我们之前的vector,list,set,map的迭代器都是单向依赖关系
只存在容器依赖迭代器而已,可是这里容器和迭代器双向依赖啊,怎么办呢?

1.解决双向依赖问题

我们可以将哈希表前置声明一下

//HashTable的前置声明
template<class K, class V, class KeyofT, class Hash>
	class HashTable;

template<class K,class V,class Ref,class Ptr,class KeyofT, class Hash>
struct __HashIterator
{....}
2.解决私有成员问题

不过我们注意到:我们的迭代器类里面只有哈希表的指针
属于哈希表的外部,而哈希表的vector数组是它的私有成员,我们在迭代器类里面是无法访问的
怎么办呢?

1.在哈希表当中加一个getTable函数,让外界能够获取到内部的vector
2.将迭代器类在哈希表当中进行友元声明

template<class K, class V,class KeyofT, class Hash>
class HashTable
{
	typedef HashNode<V> Node;
	template<class K, class V,class Ref,class Ptr, class KeyofT, class Hash>
	friend struct __HashIterator;

注意:类模板的友元声明时需要加上template<…>

2.const迭代器的问题

为了解决unordered_map的[]与const迭代器问题
我们在迭代器类里面给了三个重载版本的构造函数

template<class K,class V,class Ref,class Ptr,class KeyofT, class Hash>
struct __HashIterator
{
	typedef HashNode<V> Node;
	Node* _node;
	const HashTable<K, V, KeyofT, Hash>* _pht;
	size_t _hashi;//当前迭代器位于哈希表当中的下标
	typedef __HashIterator<K, V,Ref,Ptr, KeyofT, Hash> Self;
	typedef __HashIterator<K, V, V&, V*, KeyofT, Hash> iterator;
public:
	__HashIterator(Node* node, HashTable<K, V, KeyofT, Hash>* pht,size_t hashi)
		:_node(node)
		,_pht(pht)
		,_hashi(hashi)
	{}

	__HashIterator(Node* node,const HashTable<K, V, KeyofT, Hash>* pht, size_t hashi)
		:_node(node)
		, _pht(pht)
		, _hashi(hashi)
	{}

	__HashIterator(const iterator& it)
		:_node(it._node)
		,_pht(it._pht)
		,_hashi(it._hashi)
	{}
....
};

3.迭代器类的定义

//HashTable的前置声明
template<class K, class V, class KeyofT, class Hash>
	class HashTable;

template<class K,class V,class Ref,class Ptr,class KeyofT, class Hash>
struct __HashIterator
{
	typedef HashNode<V> Node;
	Node* _node;
	const HashTable<K, V, KeyofT, Hash>* _pht;
	size_t _hashi;//当前迭代器位于哈希表当中的下标
	typedef __HashIterator<K, V,Ref,Ptr, KeyofT, Hash> Self;
	typedef __HashIterator<K, V, V&, V*, KeyofT, Hash> iterator;
public:
	__HashIterator(Node* node, HashTable<K, V, KeyofT, Hash>* pht,size_t hashi)
		:_node(node)
		,_pht(pht)
		,_hashi(hashi)
	{}

	__HashIterator(Node* node,const HashTable<K, V, KeyofT, Hash>* pht, size_t hashi)
		:_node(node)
		, _pht(pht)
		, _hashi(hashi)
	{}

	__HashIterator(const iterator& it)
		:_node(it._node)
		,_pht(it._pht)
		,_hashi(it._hashi)
	{}

	bool operator==(const Self& s);

	bool operator!=(const Self& s);

	Ref operator*();

	Ptr operator->();

	Self& operator++();
};

4.迭代器类的完善

1.解引用和== !=

1.解引用

注意:解引用返回的是当前位置的Value,也就是节点指针里面的值
我们回顾一下节点结构体的定义
_kv这个数据才是真正的Value,因此解引用返回_kv

template<class V>
struct HashNode
{
	HashNode* _next;
	V _kv;

	HashNode(const V& kv)
		:_kv(kv)
		, _next(nullptr)
	{}
};
Ref operator*()
{
	return _node->_kv;
}

Ptr operator->()
{
	return &_node->_kv;
}
2.== !=

关于比较,跟list迭代器一样,比较节点指针的值,而不是迭代器本身的值

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

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

2.operator++

看过刚才operator++的动图演示+分析之后,我们就能很好地写出operator++来了

Self& operator++()
{
	//当前哈希桶的当前节点后面还有数据,往后走即可
	if (_node->_next)
	{
		_node = _node->_next;
	}
	//当前哈希桶的当前节点后面没有数据了,去找下一个不为空的哈希桶
	else
	{
		++_hashi;
		while (_hashi < _pht->_tables.size())
		{
			if (_pht->_tables[_hashi])
			{
				_node = _pht->_tables[_hashi];
				break;
			}
			_hashi++;
		}
		//说明找不到不为空的哈希桶了,也就是说到末尾了
		if (_hashi == _pht->_tables.size())
		{
			_node = nullptr;
		}
	}
	return *this;
}

注意:
我们这里的哈希桶是单链表,因此并不支持双向遍历,也就不支持反向迭代器,所以没有实现operator–的重载

3.迭代器类的完整代码

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

template<class K,class V,class Ref,class Ptr,class KeyofT, class Hash>
struct __HashIterator
{
	typedef HashNode<V> Node;
	Node* _node;
	const HashTable<K, V, KeyofT, Hash>* _pht;
	size_t _hashi;//当前迭代器位于哈希表当中的下标
	typedef __HashIterator<K, V,Ref,Ptr, KeyofT, Hash> Self;
	typedef __HashIterator<K, V, V&, V*, KeyofT, Hash> iterator;
public:
	__HashIterator(Node* node, HashTable<K, V, KeyofT, Hash>* pht,size_t hashi)
		:_node(node)
		,_pht(pht)
		,_hashi(hashi)
	{}

	__HashIterator(Node* node,const HashTable<K, V, KeyofT, Hash>* pht, size_t hashi)
		:_node(node)
		, _pht(pht)
		, _hashi(hashi)
	{}

	__HashIterator(const iterator& it)
		:_node(it._node)
		,_pht(it._pht)
		,_hashi(it._hashi)
	{}

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

	Ref operator*()
	{
		return _node->_kv;
	}

	Ptr operator->()
	{
		return &_node->_kv;
	}

	Self& operator++()
	{
		//当前哈希桶的当前节点后面还有数据,往后走即可
		if (_node->_next)
		{
			_node = _node->_next;
		}
		//当前哈希桶的当前节点后面没有数据了,去找下一个不为空的哈希桶
		else
		{
			++_hashi;
			while (_hashi < _pht->_tables.size())
			{
				if (_pht->_tables[_hashi])
				{
					_node = _pht->_tables[_hashi];
					break;
				}
				_hashi++;
			}
			//说明找不到不为空的哈希桶了,也就是说到末尾了
			if (_hashi == _pht->_tables.size())
			{
				_node = nullptr;
			}
		}
		return *this;
	}
};

五.哈希表的修改

1.begin和end

实现迭代器类之后,我们在哈希表里面增加begin和end
begin就是返回第一个不为空的哈希桶的节点构造出的迭代器
end直接用nullptr来构造即可

注意:如何传入哈希表指针呢? 不要忘了this指针

public:
	typedef __HashIterator<K, V, V&, V*, KeyofT, Hash> iterator;
	typedef __HashIterator<K, V,const V&,const V*, KeyofT, Hash> const_iterator;
	iterator begin()
	{
		for (int i = 0; i < _tables.size(); i++)
		{
			if (_tables[i])
			{
				return iterator(_tables[i], this, i);
			}
		}
		return iterator(nullptr, this, -1);//因为hash迭代器当中的hashi是size_t类型,所以给-1
	}

	iterator end()
	{
		return iterator(nullptr, this, -1);//因为hash迭代器当中的hashi是size_t类型,所以给-1
	}

	const_iterator begin() const
	{
		for (int i = 0; i < _tables.size(); i++)
		{
			if (_tables[i])
			{
				return const_iterator(_tables[i], this, i);
			}
		}
		return const_iterator(nullptr, this, -1);//因为hash迭代器当中的hashi是size_t类型,所以给-1
	}

	const_iterator end() const
	{
		return const_iterator(nullptr, this, -1);//因为hash迭代器当中的hashi是size_t类型,所以给-1
	}

2.insert

1.这里需要使用KeyofT类型的仿函数对象_kot来取出关键字Key
用关键字Key进行哈希映射,如何进行哈希映射呢?
使用Hash类型的仿函数对象hash即可

所以需要嵌套使用仿函数对象

我们把_kot,hash这两个仿函数对象定义成成员变量了,所以直接使用即可

2.我们只需要修改返回值,哈希映射逻辑,查找方法即可

我们要将insert的返回值修改为pair<iterator,bool>
如果有重复元素,返回重复元素所对应的节点构造出的迭代器
如果没有重复元素,返回新插入节点构造出的迭代器

pair<iterator,bool> Insert(const V& kv)
{
	//先查找在不在
	//如果在,返回false,插入失败
	iterator it = Find(_kot(kv));
	if (it != end())
	{
		return make_pair(it, false);
	}
	//扩容
	if (_n == _tables.size())
	{
		//开辟新的哈希表
		HashTable newtable;
		int newcapacity = _tables.size() * 2;
		//扩2倍
		newtable._tables.resize(newcapacity);
		//转移数据
		for (int i = 0; i < _tables.size(); i++)
		{
			Node* cur = _tables[i];
			while (cur)
			{
				Node* next = cur->_next;
				int hashi = hash(_kot(cur->_kv)) % newtable._tables.size();
				cur->_next = newtable._tables[hashi];
				newtable._tables[hashi] = cur;
				cur = next;
			}
			//防止出现野指针导致重复析构...
			_tables[i] = nullptr;
		}
		//交换两个vector,从而做到交换两个哈希表
		//通过学习vector的模拟实现,我们知道vector进行交换时只交换first,finish,end_of_storage
		_tables.swap(newtable._tables);
	}
	//1.利用哈希函数计算需要插入到那个桶里面
	int hashi = hash(_kot(kv)) % _tables.size();
	//头插
	Node* newnode = new Node(kv);
	newnode->_next = _tables[hashi];
	_tables[hashi] = newnode;
	++_n;
	return make_pair(iterator(newnode, this, hashi),true);
}

3.find

对于find我们只需要修改返回值即可
对于find和erase,我们无需通过_kot取出关键字,因为find和erase的参数类型就是K,就是关键字
而insert的类型是V,所以insert才需要_kot来取出关键字

erase的返回值依旧是bool,无需修改erase这个代码

iterator Find(const K& key)
{
	int hashi = hash(key) % _tables.size();
	Node* cur = _tables[hashi];
	while (cur)
	{
		if (_kot(cur->_kv) == key)
		{
			return iterator(cur, this, hashi);
		}
		cur = cur->_next;
	}
	return end();
}

对于构造和析构无需修改

4.哈希表的完整代码

#pragma once
#include<vector>
#include <string>
namespace hash_bucket
{
	//HashFunc<int>
	template<class K>
	//整型的哈希函数
	struct HashFunc
	{
		size_t operator()(const K& key)
		{
			return (size_t)key;
		}
	};

	//HashFunc<string>
	//string的哈希函数
	template<>
	struct HashFunc<string>
	{
		size_t operator()(const string& key)
		{
			// BKDR
			size_t hash = 0;
			for (auto e : key)
			{
				hash *= 131;
				hash += e;
			}
			return hash;
		}
	};

	template<class V>
	struct HashNode
	{
		HashNode* _next;
		V _kv;

		HashNode(const V& kv)
			:_kv(kv)
			, _next(nullptr)
		{}
	};

	//template<class K, class V, class KeyofT, class Hash = HashFunc<K>>//类模板的声明当中不能给缺省值
	template<class K, class V, class KeyofT, class Hash>
	class HashTable;

	template<class K,class V,class Ref,class Ptr,class KeyofT, class Hash>
	struct __HashIterator
	{
		typedef HashNode<V> Node;
		Node* _node;
		const HashTable<K, V, KeyofT, Hash>* _pht;
		size_t _hashi;//当前迭代器位于哈希表当中的下标
		typedef __HashIterator<K, V,Ref,Ptr, KeyofT, Hash> Self;
		typedef __HashIterator<K, V, V&, V*, KeyofT, Hash> iterator;
	public:
		__HashIterator(Node* node, HashTable<K, V, KeyofT, Hash>* pht,size_t hashi)
			:_node(node)
			,_pht(pht)
			,_hashi(hashi)
		{}

		__HashIterator(Node* node,const HashTable<K, V, KeyofT, Hash>* pht, size_t hashi)
			:_node(node)
			, _pht(pht)
			, _hashi(hashi)
		{}

		__HashIterator(const iterator& it)
			:_node(it._node)
			,_pht(it._pht)
			,_hashi(it._hashi)
		{}

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

		Ref operator*()
		{
			return _node->_kv;
		}

		Ptr operator->()
		{
			return &_node->_kv;
		}

		Self& operator++()
		{
			//当前哈希桶的当前节点后面还有数据,往后走即可
			if (_node->_next)
			{
				_node = _node->_next;
			}
			//当前哈希桶的当前节点后面没有数据了,去找下一个不为空的哈希桶
			else
			{
				++_hashi;
				while (_hashi < _pht->_tables.size())
				{
					if (_pht->_tables[_hashi])
					{
						_node = _pht->_tables[_hashi];
						break;
					}
					_hashi++;
				}
				//说明找不到不为空的哈希桶了,也就是说到末尾了
				if (_hashi == _pht->_tables.size())
				{
					_node = nullptr;
				}
			}
			return *this;
		}
	};

	template<class K, class V,class KeyofT, class Hash>
	class HashTable
	{
		typedef HashNode<V> Node;
		template<class K, class V,class Ref,class Ptr, class KeyofT, class Hash>//类模板的友元声明当中不能给缺省值
		friend struct __HashIterator;
	public:
		typedef __HashIterator<K, V, V&, V*, KeyofT, Hash> iterator;
		typedef __HashIterator<K, V,const V&,const V*, KeyofT, Hash> const_iterator;
		iterator begin()
		{
			for (int i = 0; i < _tables.size(); i++)
			{
				if (_tables[i])
				{
					return iterator(_tables[i], this, i);
				}
			}
			return iterator(nullptr, this, -1);//因为hash迭代器当中的hashi是size_t类型,所以给-1
		}

		iterator end()
		{
			return iterator(nullptr, this, -1);//因为hash迭代器当中的hashi是size_t类型,所以给-1
		}

		const_iterator begin() const
		{
			for (int i = 0; i < _tables.size(); i++)
			{
				if (_tables[i])
				{
					return const_iterator(_tables[i], this, i);
				}
			}
			return const_iterator(nullptr, this, -1);//因为hash迭代器当中的hashi是size_t类型,所以给-1
		}

		const_iterator end() const
		{
			return const_iterator(nullptr, this, -1);//因为hash迭代器当中的hashi是size_t类型,所以给-1
		}

		HashTable()
		{
			_tables.resize(10);
		}

		~HashTable()
		{
			for (int 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 V& kv)
		{
			//先查找在不在
			//如果在,返回false,插入失败
			iterator it = Find(_kot(kv));
			if (it != end())
			{
				return make_pair(it, false);
			}
			//扩容
			if (_n == _tables.size())
			{
				//开辟新的哈希表
				HashTable newtable;
				int newcapacity = _tables.size() * 2;
				//扩2倍
				newtable._tables.resize(newcapacity);
				//转移数据
				for (int i = 0; i < _tables.size(); i++)
				{
					Node* cur = _tables[i];
					while (cur)
					{
						Node* next = cur->_next;
						int hashi = hash(_kot(cur->_kv)) % newtable._tables.size();
						cur->_next = newtable._tables[hashi];
						newtable._tables[hashi] = cur;
						cur = next;
					}
					//防止出现野指针导致重复析构...
					_tables[i] = nullptr;
				}
				//交换两个vector,从而做到交换两个哈希表
				//通过学习vector的模拟实现,我们知道vector进行交换时只交换first,finish,end_of_storage
				_tables.swap(newtable._tables);
			}
			//1.利用哈希函数计算需要插入到那个桶里面
			int hashi = hash(_kot(kv)) % _tables.size();
			//头插
			Node* newnode = new Node(kv);
			newnode->_next = _tables[hashi];
			_tables[hashi] = newnode;
			++_n;
			return make_pair(iterator(newnode, this, hashi),true);
		}

		iterator Find(const K& key)
		{
			int hashi = hash(key) % _tables.size();
			Node* cur = _tables[hashi];
			while (cur)
			{
				if (_kot(cur->_kv) == key)
				{
					return iterator(cur, this, hashi);
				}
				cur = cur->_next;
			}
			return end();
		}

		bool Erase(const K& key)
		{
			int hashi = hash(key) % _tables.size();
			Node* cur = _tables[hashi], * prev = nullptr;
			while (cur)
			{
				if (_kot(cur->_kv) == key)
				{
					if (cur == _tables[hashi])
					{
						_tables[hashi] = cur->_next;
					}
					else
					{
						prev->_next = cur->_next;
					}
					return true;
				}
				prev = cur;
				cur = cur->_next;
			}
			return false;
		}
	private:
		//哈希表是一个指针数组
		vector<Node*> _tables;
		size_t _n = 0;
		Hash hash;
		KeyofT _kot;
	};
}

六.unordered_set的完整代码

unordered_set直接复用哈希表的接口即可

#pragma once
namespace hash_bucket
{
	template<class K ,class Hash = HashFunc<K>>
	class unordered_set
	{
		struct SetofKey
		{
			const K& operator()(const K& k)
			{
				return k;
			}
		};
	public:
		typedef typename HashTable<K, K, SetofKey,Hash>::const_iterator iterator;
		typedef typename HashTable<K, K, SetofKey,Hash>::const_iterator const_iterator;

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

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

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

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

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

	private:
		HashTable<K, K,SetofKey,Hash> _ht;
	};
}

七.unordered_map的完整代码

unordered_map直接复用哈希表的接口即可

#pragma once
namespace hash_bucket
{
	template<class K,class V, class Hash = HashFunc<K>>
	class unordered_map
	{
		struct MapofKey
		{
			const K& operator()(const pair<const K, V>& k)
			{
				return k.first;
			}
		};
	public:
		typedef typename HashTable<K, pair<const K, V>, MapofKey,Hash>::iterator iterator;
		typedef typename HashTable<K, pair<const K, V>, MapofKey,Hash>::const_iterator const_iterator;

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

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

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

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

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

		const_iterator begin() const
		{
			return _ht.begin();
		}

		const_iterator end() const
		{
			return _ht.end();
		}

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

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

	private:
		HashTable<K, pair<const K, V>, MapofKey,Hash> _ht;
	};
}

八.test.cpp

#include <iostream>
using namespace std;
#include "HashTable.h"
#include "MyUnOrdered_Set.h"
#include "MyUnOrdered_Map.h"
namespace hash_bucket
{
	void test1()
	{
		unordered_set<int> s;
		int a[] = { 4,14,24,34,5,7,1,15,25,3,13 };
		for (auto e : a)
		{
			s.insert(e);
		}
		unordered_set<int>::iterator it = s.begin();
		while (it != s.end())
		{
			//*it = 10;//不能改
			cout << *it << " ";
			++it;
		}
		cout << endl;
		s.erase(13);
		it = s.find(13);
		if (it != s.end())
		{
			cout << *it << endl;
		}

		unordered_set<int>::const_iterator cit = s.begin();
		while (cit != s.end())
		{
			//*cit = 10;//不能改
			cout << *cit << " ";
			++cit;
		}
	}

	void test2()
	{
		unordered_map<int, int> m;
		int a[] = { 1,2,4,5,99,331,243 };
		for (auto& e : a)
		{
			m.insert(make_pair(e, e));
		}
		unordered_map<int, int>::iterator it = m.begin();
		while (it != m.end())
		{
			//it->second = 999;//能改
			//it->first = 999;//不能改
			cout << it->first << ":" << it->second << endl;
			++it;
		}
		cout << endl;
		m.erase(4);
		it = m.find(4);
		if (it != m.end())
		{
			cout << it->first << ":" << it->second << endl;
		}
		else
		{
			cout << "没查到" << endl;
		}

		unordered_map<int, int>::const_iterator cit = m.begin();
		while (cit != m.end())
		{
			//cit->second = 999;//不能改
			//cit->first = 999;//不能改
			cout << cit->first << ":" << cit->second << endl;
			++cit;
		}
		cout << endl;
	}

	void test3()
	{
		string arr[] = {"a","b","c","ab","ab","ab","kks","qdq"};
		unordered_map<string, int> ht;
		for (auto& e : arr)
		{
			ht[e]++;
		}
		unordered_map<string, int>::iterator it = ht.begin();
		while (it != ht.end())
		{
			//it->second = 999;//能改
			//it->first = 999;//不能改
			cout << it->first << ":" << it->second << endl;
			++it;
		}
		cout << endl;
	}

}
int main()
{
	hash_bucket::test1();
	hash_bucket::test2();
	hash_bucket::test3();
	return 0;
}

在这里插入图片描述
验证成功

以上就是C++利用开散列哈希表封unordered_set,unordered_map的全部内容,希望能对大家有所帮助!

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

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

相关文章

Vue2(七):脚手架、render函数、ref属性、props配置项、mixin(混入)、插件、scoped样式

一、脚手架结构&#xff08;Vue CLI&#xff09; ├── node_modules ├── public │ ├── favicon.ico: 页签图标 │ └── index.html: 主页面 ├── src │ ├── assets: 存放静态资源 │ │ └── logo.png │ │── component: 存放组件 │ │ …

未来已来?国内10家AI大模型盘点(附体验网址)

名人说&#xff1a;莫道桑榆晚&#xff0c;为霞尚满天。——刘禹锡&#xff08;刘梦得&#xff0c;诗豪&#xff09; 创作者&#xff1a;Code_流苏(CSDN)&#xff08;一个喜欢古诗词和编程的Coder&#x1f60a;&#xff09; 目录 1、阿里云——通义千问2、科大讯飞——星火大模…

Cookie使用

文章目录 一、Cookie基本使用1、发送Cookie2、获取Cookie 二、Cookie原理三、Cookie使用细节 一、Cookie基本使用 1、发送Cookie package com.itheima.web.cookie;import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.I…

嵌入式开发--获取STM32产品系列的信息

嵌入式开发–获取STM32产品系列和容量信息 获取STM32产品系列 有时候我们需要知道当前MCU是STM32的哪一个系列&#xff0c;这当然可以从外部丝印看出来&#xff0c;但是运行在内部的软件如何知道呢&#xff1f; ST为我们提供了一个接口&#xff0c;对于STM32的所有MCU&#x…

宏宇、萨米特、新明珠、金意陶、简一、科达、力泰、道氏、SITI BT、POPPI……35家参展商发布亮点

3月18日&#xff0c;2024佛山潭洲陶瓷展&#xff08;4月18-22日&#xff09;亮点发布会在广东新媒体产业园成功举办&#xff0c;主题为“我们不一样”。 陶城报社社长、佛山潭洲陶瓷展总经理李新良代表主办方&#xff0c;发布了2024佛山潭洲陶瓷展的“不一样”&#xff1b;佛山…

TikTok账号用什么IP代理比较好?

对于运营TikTok的从业者来说&#xff0c;IP的重要性自然不言而喻。 在其他条件都正常的情况下&#xff0c;拥有一个稳定&#xff0c;纯净的IP&#xff0c;你的视频起始播放量很可能比别人高出不少&#xff0c;而劣质的IP轻则会限流&#xff0c;重则会封号。那么&#xff0c;如何…

FPGA - SPI总线介绍以及通用接口模块设计

一&#xff0c;SPI总线 1&#xff0c;SPI总线概述 SPI&#xff0c;是英语Serial Peripheral interface的缩写&#xff0c;顾名思义就是串行外围设备接口。串行外设接口总线(SPI)&#xff0c;是一种高速的&#xff0c;全双工&#xff0c;同步的通信总线&#xff0c;并且在芯片的…

Day16:LeedCode 104.二叉树的最大深度 111.二叉树最小深度 222.完全二叉树的结点个数

104. 二叉树的最大深度 给定一个二叉树 root &#xff0c;返回其最大深度。 二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。 思路:根结点最大深度max(左子树最大深度,右子树最大深度)1 终止条件,结点为null,该结点最大深度为0 class Solution {publ…

【什么是Internet?网络边缘,网络核心,分组交换 vs 电路交换,接入网络和物理媒体】

文章目录 一、什么是Internet&#xff1f;1.从具体构成角度来看2.从服务角度来看 二、网络结构1.网络边缘1.网络边缘&#xff1a;采用网络设施的面向连接服务1.1.目标&#xff1a;在端系统之间传输数据1.2.TCP服务 2.网络边缘&#xff1a;采用网络设施的无连接服务2.1目标&…

MT管理器 使用手册

MT管理器 论坛&#xff1a;https://bbs.binmt.cc/ 使用技巧系列教程&#xff1a;https://www.52pojie.cn/thread-1259872-1-1.html MT管理器 使用手册 &#xff1a;https://mt2.cn/guide/&#xff1a;https://www.bookstack.cn/read/mt-manual/80b8084f6be128c0.md&#xff…

HC-SR501人体红外传感器

一、传感器介绍 二、代码 void infrared_Init(void) { GPIO_InitTypeDef GPIO_InitStructure;RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE, ENABLE);GPIO_InitStructure.GPIO_Pin GPIO_Pin_1;GPIO_InitStructure.GPIO_Mode GPIO_Mode_IN;GPIO_InitStructure.GPIO_OT…

jsp 3.21(3)jsp基本语法

一、实验目的 jsp标记、如指令标记&#xff0c;动作标记&#xff1b;变量和方法的声明&#xff1b;Java程序片&#xff1b;Java表达式&#xff1b; 二、实验项目内容&#xff08;实验题目&#xff09; 1、编写jsp文件&#xff0c;熟悉jsp动作标记include&#xff0c;参考课本上…

python之jsonpath的使用

文章目录 介绍安装语法语法规则举例说明 在 python 中使用获取所有结构所有子节点的作者获取所有子孙节点获取所有价格取出第三本书的所有信息取出价格大于70块的所有书本从mongodb 中取数据的示例 介绍 JSONPath能在复杂的JSON数据中 查找和提取所需的信息&#xff0c;它是一…

4.1 用源文件写汇编代码

汇编语言 1. 源程序 1.1 伪指令 汇编指令是有对应的机器码的指令&#xff0c;可以被编译为机器指令&#xff0c;最终为CPU所执行伪指令没有对应的机器指令&#xff0c;最终不被CPU所执行伪指令是由编译器来执行的指令&#xff0c;编译器根据伪指令来进行相关的编译工作 1.2…

【链表】Leetcode 19. 删除链表的倒数第 N 个结点【中等】

删除链表的倒数第 N 个结点 给你一个链表&#xff0c;删除链表的倒数第 n 个结点&#xff0c;并且返回链表的头结点。 示例 1&#xff1a; 输入&#xff1a;head [1,2,3,4,5], n 2 输出&#xff1a;[1,2,3,5] 解题思路 1、使用快慢指针找到要删除节点的前一个节点。2、删…

国际数字影像产业园:专注于数字影像领域的成都数字产业园

国际数字影像产业园&#xff08;数媒大厦&#xff09;&#xff0c;作为一个专注于数字影像产业的成都数字产业园&#xff0c;其服务优势体现在三大生态服务体系&#xff1a;公共服务、公务服务、产业服务。这三大服务体系不仅共享化、数字化、产业化&#xff0c;更致力于为企业…

带你玩透浮动float布局,详解(一)

文章目录 一 认识浮动二 浮动的规则浮动的规则一代码展示 浮动规则二代码展示 浮动规则四代码展示代码展示 浮动规则五 空隙的解决方案代码展示:第一种方式 放在一行第二种解决方式&#xff08;不推荐使用这种方式&#xff09;第三种方式采用浮动&#xff08;推荐&#xff0c;统…

用户中心项目(登录 + 用户管理功能后端)

文章目录 1.登录功能-后端1.思路分析2.完成对用户名和密码的校验1.com/sun/usercenter/service/UserService.java 添加方法2.com/sun/usercenter/service/impl/UserServiceImpl.java 添加方法3.com/sun/usercenter/service/impl/UserServiceImpl.java 新增属性 3.记录用户的登录…

SpringBoot如何写好单元测试

&#x1f413;序言 Spring中的单元测试非常方便&#xff0c;可以很方便地对Spring Bean进行测试&#xff0c;包括Controller、Service和Repository等Spring Bean进行测试&#xff0c;确保它们的功能正常&#xff0c;并且不会因为应用的其他变化而出现问题。 &#x1f413;单元测…

借教室与差分

原题 题目描述 在大学期间&#xff0c;经常需要租借教室。 大到院系举办活动&#xff0c;小到学习小组自习讨论&#xff0c;都需要向学校申请借教室。 教室的大小功能不同&#xff0c;借教室人的身份不同&#xff0c;借教室的手续也不一样。  面对海量租借教室的信息&…