个人主页:Lei宝啊
愿所有美好如期而遇
前言
在看这篇文章前,建议先了解哈希表的实现:哈希表模拟实现
如果说你对哈希表的实现很清楚,那么可以直接往下看,但是本篇文章对unordered_map和unordered_set的封装使用的哈希表是哈希表模拟实现的一种更改。
我们会指出哪里做了更改以及为什么做更改,但是上篇文章提起过的这里不会再提及。
这里贴出哈希表代码:
//开散列哈希表
namespace Open
{
template<class K, class V>
struct HashNode
{
HashNode<K, V>* next;
pair<K, V> _kv;
HashNode(const pair<K, V>& kv)
:next(nullptr)
,_kv(kv)
{}
};
template<class K, class V, class Hash = HashFunc<K>>
class HashTable;
template<class K, class V, class Hash = HashFunc<K>>
class HashIterator
{
typedef HashNode<K, V> Node;
typedef HashTable<K, V, Hash> hstable;
typedef HashIterator<K, V, Hash> iterator;
public:
HashIterator(Node* n, hstable* h)
:node(n)
,hst(h)
{}
iterator& operator++()
{
if (node->next)
{
node = node->next;
}
else
{
Hash hs;
int pos = hs(node->_kv.first) % hst->_table.size();
pos++;
while (pos < hst->_table.size())
{
if (hst->_table[pos])
{
node = hst->_table[pos];
break;
}
pos++;