github代码下载
代码下载
https://github.com/Kyrie-leon/Data_Structures/tree/main/STL/Hash
一、哈希的基本概念
1.1 什么是哈希?
我们都知道在顺序结构和平衡树中,查找一个元素通过比对关键值来查找。顺序查找时间复杂度为O(N),平衡树中为树的高度,即O( l o g 2 N log_2N log2N),简单来说,搜索的效率取决于搜索过程中元素的比较次数。
理想的搜索方法:可以不经过任何比较,一次直接从表中得到要搜索的元素。 如果构造一种存储结构,通过某种函数(hashFunc)使元素的存储位置与它的关键码之间能够建立一一映射的关系,那么在查找时通过该函数可以很快找到该元素。
当向该结构中:
- 插入元素
根据待插入元素的关键码,以此函数计算出该元素的存储位置并按此位置进行存放 - 搜索元素
对元素的关键码进行同样的计算,把求得的函数值当做元素的存储位置,在结构中按此位置取元素比较,若关键码相等,则搜索成功
该方式即为哈希(散列)方法,哈希方法中使用的转换函数称为哈希(散列)函数,构造出来的结构称为哈希表(Hash Table)(或者称散列表)
举个栗子:有如下集合{1,7,6,4,5,9};
- 哈希函数设置为:hash(key) = key % capacity;
- capacity为存储元素底层空间总的大小。
用该方法进行搜索不必进行多次关键码的比较,因此搜索的速度比较快 .
1.2 哈希冲突
如上图所示,当元素44按照哈希函数计算出哈希地址为4,与元素4的哈希地址相同,这种现象就是哈希冲突(哈希碰撞)。
该如何处理哈希冲突呢?
1.3 哈希函数
引起哈希冲突的一个原因可能是:哈希函数设计不够合理。
哈希函数设计原则:
- 哈希函数的定义域必须包括需要存储的全部关键码,而如果散列表允许有m个地址时,其值域必须在0到m-1之间
- 哈希函数计算出来的地址能均匀分布在整个空间中哈
- 希函数应该比较简单
1.4 常见的哈希函数
<1> 直接定制法–(常用)
取关键字的某个线性函数为散列地址:
H a s h ( K e y ) = A ∗ K e y + B Hash(Key)= A*Key + B Hash(Key)=A∗Key+B
- 优点:简单、均匀
- 缺点:需要事先知道关键字的分布情况
- 使用场景:适合查找比较小且连续的情况
<2> 除留余数法–(常用)
设散列表中允许的地址数为m,取一个不大于m,但最接近或者等于m的质数p作为除数,按照哈希函数:
H
a
s
h
(
k
e
y
)
=
k
e
y
%
p
(
p
<
=
m
)
Hash(key) = key\% p(p<=m)
Hash(key)=key%p(p<=m)
<3> 平方取中法–(了解)
假设关键字为1234,对它平方就是1522756,抽取中间的3位227作为哈希地址; 再比如关键字为4321,对它平方就是18671041,抽取中间的3位671(或710)作为哈希地址
- 平方取中法比较适合:不知道关键字的分布,而位数又不是很大的情况
注意:
哈希函数设计的越精妙,产生哈希冲突的可能性就越低,但是无法避免哈希冲突
二、 哈希冲突解决
解决哈希冲突两种常见的方法是:闭散列和开散列
2.1 闭散列
闭散列:也叫开放定址法,当发生哈希冲突时,如果哈希表未被装满,说明在哈希表中必然还有空位置,那么可以把key存放到冲突位置中的“下一个” 空位置中去。
那如何寻找下一个空位置呢?
<1> 线性探测
比如1.2中的场景,现在需要插入元素44,先通过哈希函数计算哈希地址,hashAddr为4,因此44理论上应该插在该位置,但是该位置已经放了值为4的元素,即发生哈希冲突。
简单来说,线性探测就是从冲突的位置开始,依次向后探测,直到找到一个空位置为止。
- 插入
1. 通过哈希函数获取待插入元素在哈希表中的位置
2. 如果该位置中没有元素则直接插入新元素,如果该位置中有元素发生哈希冲突,使用线性探测找到下一个空位置,插入新元素
- 删除
采用闭散列处理哈希冲突时,不能随便物理删除哈希表中已有的元素,若直接删除元素会影响其他元素的搜索。比如删除元素4,如果直接删除掉,44查找起来可能会受影响。因此线性探测采用标记的伪删除法来删除一个元素
2.2 开散列
闭散列在实践中很少使用,因为会发生践踏效应,即一个位置被占用导致后面所有的位置都去占用别人的位置。
<1> 开散列概念
开散列法又叫链地址法(开链法),首先对关键码集合用散列函数计算散列地址,具有相同地址的关键码归于同一子集合,每一个子集合称为一个桶,各个桶中的元素通过一个单链表链接起来,各链表的头结点存储在哈希表中。
从上图可以看出,开散列中每个桶中放的都是发生哈希冲突的元素。
负载因子控制在1,平均每个桶下挂一个节点
优势
- 不同的位置冲突值不再互相干扰踩踏
- 空间利用率更高,负载因子一般可以控制到1
Q1:如果一个桶挂了大量节点怎么解决?
用红黑树替代
Q2:给你一个key做map和unordered_map的key,区别是什么?
- map支持比较大小
- unordered_map支持取模
三、代码实现
3.1 HashTable.hpp
#pragma once
template<class K>
struct Hash
{
size_t operator()(const K &key)
{
return key;
}
};
//模板特化,用于处理string类型
template<>
struct Hash<string>
{
//字符串中的字符累加和
size_t operator()(const string &s)
{
int hash = 0;
for (auto& ch : s)
{
hash += ch;
}
return hash;
}
};
//静态全局变量
static size_t GetNextPrime(size_t prime)
{
//全部的素数数组一共28个
static const int PRIMECOUNT = 28;
static const size_t primeList[PRIMECOUNT] =
{
53ul, 97ul, 193ul, 389ul, 769ul,
1543ul, 3079ul, 6151ul, 12289ul, 24593ul,
49157ul, 98317ul, 196613ul, 393241ul, 786433ul,
1572869ul, 3145739ul, 6291469ul, 12582917ul, 25165843ul,
50331653ul, 100663319ul, 201326611ul, 402653189ul, 805306457ul,
1610612741ul, 3221225473ul, 4294967291ul
};
//获取下一次的素数,只要比传进来的素数大就可以返回
size_t i = 0;
for (; i < PRIMECOUNT; ++i)
{
if (primeList[i] > prime)
return primeList[i];
}
return primeList[i];
}
//闭散列
namespace Close {
enum State {
EMPTY,
EXIST,
DELETE
};
template <class T>
struct HashNode
{
State _state; //状态
T _t; //存储值
};
template<class K, class T, class HashFunc = Hash<K>>
class HashTable
{
public:
//1.插入元素
bool Insert(const T &t)
{
//1.判断是否需要增容,通过负载因子判断0.7
if (_tables.size() == 0 || _size * 10 / _tables.size() == 7) //0.7转为整形只有0,因此让分子*10
{
size_t new_size = GetNextPrime(_tables.size()); //获取增容大小
//1.重建一个新哈希表
HashTable<K, T, HashFunc> new_hf;
//2.扩容新的哈希表
new_hf._tables.resize(new_size);
//3.遍历旧表,插入新表,通过EXIST标志来判断
for (auto &e : _tables)
{
if (e._state == EXIST)
new_hf.Insert(e._t); //复用冲突时探测的逻辑
}
//4.交换新旧地址空间,完成扩容
_tables.swap(new_hf._tables);
}
//2.判断是否存在,如果存在则返回false
HashNode<T> *ret = Find(t);
if (ret)
return false;
//3.插入元素
HashFunc hf;
//a.哈希函数转换获取初始位置
size_t start = hf(t) % _tables.size();
size_t index = start;
size_t i = 1;
//b.通过状态解决哈希冲突线性探测
while (_tables[index]._state == EXIST)
{
index = start + i;
//细节:index如果一直加下去会出现越界,因此构造成环形队列
index %= _tables.size();
i++;
}
//c.将元素插入更新状态
_tables[index]._t = t;
_tables[index]._state = EXIST;
//d.有效元素+1
++_size;
return true;
}
//2.查找元素
HashNode<T>* Find(const K &key)
{
//1.哈希函数转换
HashFunc hf;
size_t start = hf(key) % _tables.size();
size_t index = start;
size_t i = 1;
//2.线性探测,找空位置
while (_tables[index]._state != EMPTY)
{
if (_tables[index]._t == key
&& _tables[index]._state == EXIST)
{
return &_tables[index];
}
index = start + i;
index %= _tables.size();
++i;
}
return nullptr;
}
//3.删除
bool Erase(const K &k)
{
//1.复用find找到这个元素
HashNode<T> *ret = Find(k);
//2.状态置DELETE
if (ret == nullptr)
{
return false;
}
else
{
//伪删除
ret->_state = DELETE;
return true;
}
}
private:
vector<HashNode<T>> _tables; //哈希表
size_t _size = 0; //有效数据个数
};
void TestHashTable()
{
HashTable<int, int> ht;
ht.Insert(5);
ht.Insert(15);
ht.Insert(25);
ht.Insert(35);
ht.Insert(45);
ht.Insert(55);
ht.Insert(65);
ht.Insert(75);
ht.Insert(85);
ht.Insert(95);
ht.Insert(108);
HashTable<string, string> st;
st.Insert("sort");
st.Insert("insert");
}
}
//开散列哈希桶
namespace Open {
template<class T>
//哈希结点结构
struct HashLinkNode
{
T _t; //元素
HashLinkNode<T> *_next; //指针指向下一个节点
//构造函数
HashLinkNode(const T &t)
:_t(t)
, _next(nullptr)
{}
};
//前置声明
template<class K, class T, class KeyOfT, class hash>
class HashTable;
//迭代器结构实现
template<class K, class T, class Ref, class Ptr, class KeyOfT, class hash>
struct HashIterator
{
typedef HashIterator<K, T, Ref, Ptr, KeyOfT, hash> Self;
typedef HashLinkNode<T> Node;
Node* _node; //哈希结点指针
HashTable<K, T, KeyOfT, hash>* _pht; //哈希表
//构造函数
HashIterator(Node* node, HashTable<K, T, KeyOfT, hash>* pht)
:_node(node)
,_pht(pht)
{}
//迭代器操作符实现
//解引用
Ref operator*()
{
return _node->_t;
}
//->操作符实现
Ptr operator->()
{
return &(_node->_t);
}
bool operator!=(const Self& s) const
{
return _node != s._node;
}
//++it
Self operator++()
{
// 1、当前桶还有数据,继续走
// 2、当前桶没有数据,跳到下一个桶,从第一个开始
if (_node->_next)
{
_node = _node->_next;
}
else
{
KeyOfT kot;
//找到下一个桶
size_t index = _pht->HashFunc(kot(_node->_t), _pht->_tables.size()); //哈希函数计算下标index
index++;
while (index < _pht->_tables.size())
{
//哈希表index这个桶不为空,则让node指向这个同继续遍历
if (_pht->_tables[index])
{
_node = _pht->_tables[index];
break;
}
else
{
index++;
}
}
if (index == _pht->_tables.size())
{
_node = nullptr; //没有找到下一个桶
}
}
return *this;
}
};
template<class K, class T, class KeyOfT, class hash = Hash<K>>
class HashTable
{
typedef HashLinkNode<T> Node;
friend struct HashIterator <K, T, T&, T*, KeyOfT, hash>;
public:
//迭代器
typedef HashIterator<K, T, T&, T*, KeyOfT, hash> Iterator;
typedef HashIterator<K, T, const T&, const T*, KeyOfT, hash> ConstIterator; //const迭代器
Iterator Begin()
{
for (size_t i = 0; i < _tables.size(); ++i)
{
if (_tables[i])
{
return Iterator(_tables[i], this);
}
}
return End();
}
Iterator End()
{
return Iterator(nullptr, this);
}
//哈希函数
size_t HashFunc(const K& key, size_t n)
{
hash hf;
size_t ki = hf(key);
return ki % n;
}
//插入,头插
pair<Iterator, bool> Insert(const T& t)
{
KeyOfT kot;
//负载因子==1时增容
if (_size == _tables.size())
{
//获取新的空间大小
size_t newSize = GetNextPrime(_tables.size());
vector<Node*> newTables;
newTables.resize(newSize, nullptr); //创建表重新插入哈希数据
//遍历哈希表
for (size_t i = 0; i < _tables.size(); ++i)
{
Node* cur = _tables[i]; //遍历i下的每个点
while (cur)
{
size_t index = HashFunc(kot(cur->_t), newSize); //重新计算下标
//头插
Node* next = cur->_next;
cur->_next = newTables[index];
newTables[index] = cur; //节点插入新哈希表
cur = next;
}
_tables[i] = nullptr; //虽然节点挂在新表,但是旧表仍指向节点,因此将i节点遍历完置空
}
newTables.swap(_tables);
}
size_t index = HashFunc(kot(t), _tables.size());
//查找t在不在
Node* cur = _tables[index];
while (cur)
{
if (kot(cur->_t) == kot(t))
return make_pair(Iterator(cur, this), false);
cur = cur->_next;
}
//头插
Node* newNode = new Node(t);
newNode->_next = _tables[index];
_tables[index] = newNode;
return make_pair(Iterator(newNode, this), true);
}
//查找
Iterator Find(const K& key)
{
KeyOfT kot;
size_t index = HashFunc(kot(key), _tables.size()); //找到key对应的hash下标
Node* cur = _tables[index];
while(cur)
{
if(kot(cur->_t) == kot(key))
return Iterator(cur, this);
cur = cur->_next;
}
return End();
}
//删除
bool Erase(const K& key)
{
size_t index = HashFunc(kot(key), _tables.size()); //找到key在哈希表中下标
Node* cur = _tables[index];
Node* prev = nullptr;
while (cur)
{
//找到
if (kot(key) == kot(cur->_t))
{
//1.prev为空直接把cur->_next挂到index桶下
//2.prev不为空,只用将prev指向cur->_next
if (prev = nullptr)
{
_tables[index] = cur->_next;
}
else
{
prev->_next = cur->_next;
}
delete cur;
return true;
}
//没找到cur后移
else
{
prev = cur;
cur = cur->_next;
}
}
return false;
}
private:
vector<Node*> _tables;
size_t _size = 0;
};
}
3.2 unordered_map.h
#pragma once
#include "HashTable.hpp"
namespace leon
{
template<class K, class V, class hash = Hash<K>>
class unordered_map
{
struct MapKOfT
{
const K& operator()(const pair<const K, V>& kv)
{
return kv.first;
}
};
public:
typedef typename Open::HashTable<K, pair<const K, V>, MapKOfT, hash>::Iterator iterator;
iterator begin()
{
return _ht.Begin();
}
iterator end()
{
return _ht.End();
}
pair<iterator, bool> insert(const pair<const K, V>& kv)
{
return _ht.Insert(kv);
}
V& operator[](const K& key)
{
pair<iterator, bool> ret = insert(make_pair(key, V()));
return ret.first->second;
}
private:
Open::HashTable<K, pair<const K, V>, MapKOfT, hash> _ht;
};
void test_unordered_map()
{
leon::unordered_map<string, string> dict;
dict["sort"] = "排序";
dict["hash"] = "哈希";
for (auto& e : dict)
{
cout << e.first << ":" << e.second << endl;
}
}
}
3.3 unordered_set.h
#pragma once
#include "HashTable.hpp"
namespace leon
{
template<class K, class hash = Hash<K>>
class unordered_set
{
struct SetKOfT
{
const K& operator()(const K& k)
{
return k;
}
};
public:
typedef typename Open::HashTable<K, K, SetKOfT, hash>::Iterator iterator;
iterator begin()
{
return _t.Begin();
}
iterator end()
{
return _t.End();
}
pair<iterator, bool> insert(const K& k)
{
return _t.Insert(k);
}
private:
Open::HashTable<K, K, SetKOfT, hash> _t;
};
void test_unordered_set()
{
unordered_set<int> us;
us.insert(1);
us.insert(54);
us.insert(58);
us.insert(58);
us.insert(59);
us.insert(100);
unordered_set<int>::iterator it = us.begin();
while (it != us.end())
{
cout << *it << " ";
++it;
}
cout << endl;
}
}