C++哈希表(unordered_map和unordered_set)


以哈希表为底层的unordered1_map和unordered_set相对于以红黑树为底层的map和set而言,在数据无序时效率更高。unordered1_map和unordered_set遍历出来的数据是无序的。

开放地址法

思路:创建一个数组,每个位置只能存储一个值,当插入一个值时,通过一个映射函数映射到该数组上,如果当前映射到的位置有值存在,就再以某种函数放到其余位置。每个位置的状态有三种,存在,删除和为空,以此方便我们查找和删除。

闭散列哈希表

开放地址法实现的哈希表极容易出现哈希冲突的情况,因此我们可以通过闭散列实现哈希表来降低哈希冲突。
闭散列思路:仍是一个数组,但是该数组中存储的是一个指针,该指针指向一个链表或一棵树,链表或树中存储的是对应的数据,也就是将原本映射到同一位置的数据,以链表或树的方式组织起来,同时我们把这个指针指向的结构称为桶,也就是哈希桶。
下面我们以闭散列哈希表为底层封装容器unordered_map和unordered_set

节点

数组中存储的是桶节点指针,节点的结构如下

template<class T>
struct HashNode
{
	T _data;
	HashNode<T>* _next;
	HashNode(const T& data)
		:_data(data)
		, _next(nullptr)
	{}

};

存储的数据分别是_data数据和指向下一个桶节点的_next指针

哈希表

哈希表中有两个成员变量分别是存储每个哈希桶节点指针的数组和哈希表中一共存储的数据个数

template<class K, class T, class KeyOfT, class HashFunc>
class HashTable
{
	typedef HashNode<T> Node;
private:
	vector<Node*> _table;//指针数组
	size_t _n = 0; //存储了多少个数据
};

为什么还要保存哈希表中存储的数据个数?
如果存储的数据个数过多,而数组的长度较小就会导致哈希表负载因子过高,当负载因子大于某一个值时,就需要我们对这个数组进行扩容,因此_n的作用是方便我们计算负载因子,从而判断是否需要扩容。

struct DefaultHashFunc

通过该仿函数将不同类型的key值都转换成整型,方便我们通过映射函数映射到哈希表的某一个哈希桶

template<class K>
struct DefaultHashFunc//此函数作用是什么 通过仿函数将key变成整型,从而可以进行取余,建立映射关系
{
	size_t operator()(const K& key)
	{
		return (size_t)key;
	}
};

template<>
struct DefaultHashFunc<string>//特化,指定接受的参数类型为string
{
	size_t operator()(const string& str)
	{
		return str[0];
	}
};

对于string类型我们这里以取第一个字符转化为整型为例,你也可以取前n个字符并以某种的运算确定该类型的映射值

KeyOfMap

struct KeyOfMap
{
	const	K& operator()(const pair<K, V>& kv)
	{
		return kv.first;
	}
};

KeyOfSet

struct KeyOfSet
{
	const K& operator()(const K& key)
	{
		return key;
	}
};

Find

通过key值来查找当前值是否存在,思路:先判断出当前key值可能位于哪一个桶,然后再在桶中逐个查找数据,如果找到了返回当前节点的迭代器,如果没找到则返回迭代器end()
但是当前有两个问题:
1.传过来的key值类型我们是不确定的,他可能不是整型不能放到映射函数中进行运算,因此我们需要一个函数将这个key值转换成整型,然后再通过函数映射到哈希表的某一个桶,再在这个同种查找该数据是否存在
2.对于unordered_map和unordered_set分别存储的是键值对和键值,因此我们需要把他们中的key值取出来,然后才能与要查找的key值判断是否相等,因此可以选择在unordered_map和unordered_set第一层封装那里,分别设计对应的仿函数,用于取出这两个容器的key值。

iterator Find(const K& key)
{
	HashFunc hf;
	KeyOfT kot;
	size_t hashi = hf(key) % _table.size();
	Node* cur = _table[hashi];
	while(cur)
	{
		if (kot(cur->_data) == key)
		{
			return iterator(cur, this);
		}
		cur = cur->_next;
	}
	return end();
}

Insert

数据的插入思路:
1.先判断当前值在哈希表中是否存在,如果存在就不用再插入了,并返回一个键值对,键值对中first存储指向该节点的迭代器,second为bool值false
2.其次判断该哈希表是否需要扩容,我们定义当负载因子值为1时就进行扩容,也就是_table.size() == _n就扩容
3.最后再插入

pair<iterator, bool> Insert(const T& data)
{
	KeyOfT kot;
	//如果已存在就返回false
	iterator it = Find(kot(data));
	if (it != end())
	{
		return make_pair(it, false);
	}

	HashFunc hf;
	size_t hashi = hf(kot(data)) / _table.size();
	//扩容
	if (_table.size() == _n)
	{
		size_t newsize = _table.size() * 2;
		vector<Node*> newtable;
		newtable.resize(newsize);
		//把原容器中的数据重新插入到新容器中
		for (size_t i = 0; i < _table.size(); i++)
		{
			Node* cur = _table[i];
			while (cur)
			{
				Node* next = cur->_next;
				hashi = hf(kot(cur->_data)) % newtable.size();
				cur->_next = newtable[hashi];
				newtable[hashi] = cur;
				cur = next;
			}
			_table[i] = nullptr;//将原表置空
		}
		newtable.swap(_table);
	}

	//插入
	hashi = hf(kot(data)) % _table.size();
	Node* newnode = new Node(data);
	newnode->_next = _table[hashi];
	_table[hashi] = newnode;
	_n++;
	return make_pair(iterator(newnode, this), true);
}

迭代器

对于以往的容器,我们在实现迭代器时,它的构造函数只需要传过来一个节点指针过来即可,但是对于unordered_map和unordered_set,我们选择把哈希表指针也传过来,为什么?
因为我们在实现++操作时,不仅要去访问当前节点所在桶中的下一个节点,还可能要去访问下一个桶中的节点,因此我们把整个哈希表都传过来,以利于我们实现++操作。
两种情况
1.该节点的_next指针不为空
2.该节点的_next指针为空,就需要我们再去访问下一个桶了
为什么要在迭代器中实现一个构造函数只传Iterator的构造函数?
因为我们在第一层封装时Insert的返回值是一个普通迭代器,但是unordered_set中的迭代器都是const的,我们要返回的迭代器也需要是const的,因此我们设计出一个构造函数将普通迭代器构造**出一个const迭代器。不写这个构造函数不行吗?不是可以由普通迭代器通过权限缩小成const迭代器吗?**要注意一个误区这里的迭代器是类型定义为

typedef HTIterator<K, T, T*, T&, KeyOfT, HashFunc> iterator;
typedef HTIterator<K, T, const T*, const T&, KeyOfT, HashFunc> const_iterator;

HTIterator是一个整体,这是两个不同的类型,没有权限放大与缩小这一说,不要把概念混淆了

template <class K, class T, class Ptr, class Ref, class KeyOfT, class HashFunc>
struct HTIterator
{
	typedef HashNode<T> Node;
	typedef HTIterator<K, T, Ptr, Ref, KeyOfT, HashFunc> Self;
	typedef const HTIterator<K, T, T*, T&, KeyOfT, HashFunc> Iterator;
	Node* _node;
	const HashTable<K, T, KeyOfT, HashFunc>* _pht;
	//HTIterator(Node* node, HashTable<K, T, KeyOfT, HashFunc>* pht)//把哈希表指针也传过来,便于我们使用
	//	:_node(node)
	//	, _pht(pht)
	//{

	//}

	HTIterator(Node* node, const HashTable<K, T, KeyOfT, HashFunc>* pht)
		:_node(node)
		, _pht(pht)
	{

	}

	HTIterator(const Iterator& it)
		:_node(it._node)
		, _pht(it._pht)
	{

	}

	Self& operator++()
	{
		if (_node->_next)
		{
			_node = _node->_next;
		}
		else//当前桶结束,找下一个节点不为空的桶
		{
			HashFunc hf;
			KeyOfT kot;
			size_t hashi = hf(kot(_node->_data)) % _pht->_table.size();
			++hashi;
			while (hashi < _pht->_table.size())
			{
				if (_pht->_table[hashi])
				{
					_node = _pht->_table[hashi];
					return *this;
				}
				++hashi;
			}
			_node = nullptr;
		}
		
		return *this;
	}

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

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

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

前置声明

因为我们不仅要在哈希表类中访问迭代器,还要在迭代器中访问哈希表类对象,这就会导致哪个类放在前面会报错,因为程序编译是自上而下进行查找的,因此我们要把放在后面的类在另一个类之前进行类声明,表明这个类是存在的

//前置声明
template<class K, class T, class KeyOfT, class HashFunc = DefaultHashFunc<K>> class HashTable;

哈希表的友元类

因为迭代器要访问哈希表类private私密成员指针数组和_n,因此我们选择把迭代器类声明为哈希表类的友元类

template<class K, class T, class KeyOfT, class HashFunc>
class HashTable
{
//友元声明,要加上模版
template<class K, class T, class Ptr, class Ref, class KeyOfT, class HashFunc> friend struct HTIterator;
}

begin()和end()

哈希表类中定义普通迭代器和const 迭代器

		typedef HashNode<T> Node;
		
	public:
		typedef HTIterator<K, T, T*, T&, KeyOfT, HashFunc> iterator;
		typedef HTIterator<K, T, const T*, const T&, KeyOfT, HashFunc> const_iterator;
		
	HashTable()
	{
		_table.resize(10);
	}
	
	iterator begin()
	{
		for (size_t i = 0; i < _table.size(); i++)
		{
			Node* cur = _table[i];
			if (cur)
			{
				return iterator(cur, this);
			}
		}
		return iterator(nullptr, this);
	}

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

	const_iterator begin() const
	{
		for (size_t i = 0; i < _table.size(); i++)
		{
			Node* cur = _table[i];
			if (cur)
			{
				return const_iterator(cur, this);
			}
		}
		return const_iterator(nullptr, this);
	}

	const_iterator end() const
	{
		return const_iterator(nullptr, this);
	}

unordered_map类

#pragma once
#include "HashTable.h"

namespace sw
{
	template <class K, class V>
	class UnorderedMap
	{
		struct KeyOfMap
		{
			const	K& operator()(const pair<K, V>& kv)
			{
				return kv.first;
			}
		};
		

	public:
		//为什么要加typename?
		typedef typename sw::HashTable<K, pair<const K, V>, KeyOfMap>::iterator iterator;
		typedef typename sw::HashTable<K, pair<const K, V>, KeyOfMap>::const_iterator const_iterator;
		pair<iterator, bool> insert(const pair<K, V>& kv)
		{
			return hash_bucket.Insert(kv);
		}

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

		V& operator[](const K& key)
		{
			pair<iterator, bool> ret = hash_bucket.Insert(make_pair(key, V()));
			return ret.first->second;//等价于(*ret.first).second;
		}

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

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

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

		const_iterator end() const
		{
			return hash_bucket.end();
		}
	private:
		HashTable<K, pair<const K, V>, KeyOfMap> hash_bucket;
	};
}

unordered_set类

#pragma once
#include "HashTable.h"

namespace sw
{
	template <class K>
	class UnorderedSet
	{
		struct KeyOfSet
		{
			const K& operator()(const K& key)
			{
				return key;
			}
		};
		
	public:
		typedef typename sw::HashTable<K, K, KeyOfSet>::const_iterator iterator;
		typedef typename sw::HashTable<K, K, KeyOfSet>::const_iterator const_iterator;
		pair<iterator, bool> insert(const K& key)
		{
			return hash_bucket.Insert(key);
		}

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

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

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

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

		const_iterator end()const 
		{
			return hash_bucket.end();
		}
	private:
		HashTable<K, K, KeyOfSet> hash_bucket;
	};
}

迭代器类

template <class K, class T, class Ptr, class Ref, class KeyOfT, class HashFunc>
struct HTIterator
{
	typedef HashNode<T> Node;
	typedef HTIterator<K, T, Ptr, Ref, KeyOfT, HashFunc> Self;
	typedef const HTIterator<K, T, T*, T&, KeyOfT, HashFunc> Iterator;
	Node* _node;
	const HashTable<K, T, KeyOfT, HashFunc>* _pht;
	//HTIterator(Node* node, HashTable<K, T, KeyOfT, HashFunc>* pht)//把哈希表指针也传过来,便于我们使用9.18 18:52
	//	:_node(node)
	//	, _pht(pht)
	//{

	//}

	HTIterator(Node* node, const HashTable<K, T, KeyOfT, HashFunc>* pht)
		:_node(node)
		, _pht(pht)
	{

	}

	HTIterator(const Iterator& it)
		:_node(it._node)
		, _pht(it._pht)
	{

	}

	Self& operator++()
	{
		if (_node->_next)
		{
			_node = _node->_next;
		}
		else//当前桶结束,找下一个节点不为空的桶
		{
			HashFunc hf;
			KeyOfT kot;
			size_t hashi = hf(kot(_node->_data)) % _pht->_table.size();
			++hashi;
			while (hashi < _pht->_table.size())
			{
				if (_pht->_table[hashi])
				{
					_node = _pht->_table[hashi];
					return *this;
				}
				++hashi;
			}
			_node = nullptr;
		}
		
		return *this;
	}

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

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

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

哈希表类

template<class K, class T, class KeyOfT, class HashFunc>
class HashTable
{
	template<class K, class T, class Ptr, class Ref, class KeyOfT, class HashFunc>
	friend struct HTIterator;

	typedef HashNode<T> Node;
	
	//友元声明,要加上模版
public:
	typedef HTIterator<K, T, T*, T&, KeyOfT, HashFunc> iterator;
	typedef HTIterator<K, T, const T*, const T&, KeyOfT, HashFunc> const_iterator;
	HashTable()
	{
		_table.resize(10);
	}
	
	iterator begin()
	{
		for (size_t i = 0; i < _table.size(); i++)
		{
			Node* cur = _table[i];
			if (cur)
			{
				return iterator(cur, this);
			}
		}
		return iterator(nullptr, this);
	}

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

	const_iterator begin() const
	{
		for (size_t i = 0; i < _table.size(); i++)
		{
			Node* cur = _table[i];
			if (cur)
			{
				return const_iterator(cur, this);
			}
		}
		return const_iterator(nullptr, this);
	}

	const_iterator end() const
	{
		return const_iterator(nullptr, this);
	}

	pair<iterator, bool> Insert(const T& data)
	{
		KeyOfT kot;
		//如果已存在就返回false
		iterator it = Find(kot(data));
		if (it != end())
		{
			return make_pair(it, false);
		}

		HashFunc hf;
		size_t hashi = hf(kot(data)) / _table.size();
		//扩容
		if (_table.size() == _n)
		{
			size_t newsize = _table.size() * 2;
			vector<Node*> newtable;
			newtable.resize(newsize);
			//把原容器中的数据重新插入到新容器中
			for (size_t i = 0; i < _table.size(); i++)
			{
				Node* cur = _table[i];
				while (cur)
				{
					Node* next = cur->_next;
					hashi = hf(kot(cur->_data)) % newtable.size();
					cur->_next = newtable[hashi];
					newtable[hashi] = cur;
					cur = next;
				}
				_table[i] = nullptr;//将原表置空
			}
			newtable.swap(_table);
		}

		//插入
		hashi = hf(kot(data)) % _table.size();
		Node* newnode = new Node(data);
		newnode->_next = _table[hashi];
		_table[hashi] = newnode;
		_n++;
		return make_pair(iterator(newnode, this), true);
	}

	iterator Find(const K& key)
	{
		HashFunc hf;
		KeyOfT kot;
		size_t hashi = hf(key) % _table.size();
		Node* cur = _table[hashi];
		while(cur)
		{
			if (kot(cur->_data) == key)
			{
				return iterator(cur, this);
			}
			cur = cur->_next;
		}
		return end();
	}

	bool Erase(const K& key)
	{
		HashFunc hf;
		size_t hashi = hf(key) % _table.size();
		Node* cur = _table[hashi];
		//当存在时,分两种情况
		//1.key节点在当前桶的第一个位置,_table[hashi]就指向key节点2.key节点在当前桶的后面位置
		KeyOfT kot;
		if (kot(cur->_data) == key)
		{
			_table[hashi] = cur->_next;
			delete cur;
			--_n;
			return true;
		}
		else
		{
			Node* prev = cur;
			while (cur)
			{
				if (kot(cur->_data) == key)
				{
					prev->_next = cur->_next;
					delete cur;
					--_n;
					return true;
				}
				prev = cur;
				cur = cur->_next;
			}
		}
		
		return false;
	}

private:
	vector<Node*> _table;//指针数组
	size_t _n = 0; //存储了多少个数据
};

桶节点和类的前置声明

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 HashFunc = DefaultHashFunc<K>> class HashTable;

key值转size_t类型

template<class K>
struct DefaultHashFunc//此函数作用是什么9.16 11:26 通过仿函数将key变成整型,从而可以进行取余,建立映射关系
{
	size_t operator()(const K& key)
	{
		return (size_t)key;
	}
};

template<>
struct DefaultHashFunc<string>//特化,指定接受的参数类型为string
{
	size_t operator()(const string& str)
	{
		return str[0];
	}
};

总结

哈希表封装unordered_map和unordered_set具体步骤
一、哈希表类
1.定义桶节点,桶节点中包含存储的值和指向下一个桶节点的指针
2.定义哈希表类,类中成员变量分别为一个数组,数组中的值指向一个桶的节点指针
3.各类成员函数实现,通过两个DefaultHashFunc函数来获取key值所对应的整型值
二、迭代器
1.迭代器类需要两个成员变量分别为哈希表指针和桶节点指针
2.实现迭代器的++,==和!=,指针,引用等操作
3.实现一个构造函数,把普通迭代器转换成const迭代器,如果传过来的是普通迭代器那么这个构造函数就为构造函数,如果传过来的是const迭代器那么这个函数就为拷贝构造
4.哈希表类中typedef迭代器,分别为const迭代器和普通迭代器
三、封装unordered_map和unordered_set
1.类中成员变量都为哈希表,当上层调用unordered_map和unordered_set类成员函数时,我们都通过该成员去调用底层哈希表类所对应的函数
2.unordered_set中的key不允许被修改,因此我们把它的迭代器都定义为const迭代器即可
3.对于unordered_map而言它的key也不允许被修改,但是value可以被修改,因此我们就不能让它像unordered_set一样将迭代器都定义为const的,而是它该封装类中的成员变量中的K声明为const的 HashTable<K, pair<const K, V>, KeyOfMap> hash_bucket;
4.在这两个类中分别实现仿函数,用于返回该类的key值

  • 31
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦想很美

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值