目录
[6.1 除法散列法/除留余数法](#6.1 除法散列法/除留余数法)
[6.2 乘法散列法(了解)](#6.2 乘法散列法(了解))
[6.3 全域散列法(了解)](#6.3 全域散列法(了解))
[6.4 其他方法(了解)](#6.4 其他方法(了解))
[7.1 开放定址法](#7.1 开放定址法)
[7.1.1 线性探测](#7.1.1 线性探测)
[7.1.2 二次探测](#7.1.2 二次探测)
[7.1.3 双重散列(了解)](#7.1.3 双重散列(了解))
[7.2 开放定址法代码实现](#7.2 开放定址法代码实现)
[7.2.1 开放定址法的哈希表结构](#7.2.1 开放定址法的哈希表结构)
[7.2.2 Insert函数实现](#7.2.2 Insert函数实现)
[7.2.3 Find函数实现](#7.2.3 Find函数实现)
[7.2.4 Erase函数实现](#7.2.4 Erase函数实现)
[7.2.5 扩容](#7.2.5 扩容)
[7.2.6 Key不能取模的问题](#7.2.6 Key不能取模的问题)
[7.2.6.1 key是string类型](#7.2.6.1 key是string类型)
[7.2.6.2 key是Date类型](#7.2.6.2 key是Date类型)
[7.2.6.3 unordered_map的模板参数的理解](#7.2.6.3 unordered_map的模板参数的理解)
[7.2.7 Hashtable.h代码](#7.2.7 Hashtable.h代码)
[7.2.8 test.cpp](#7.2.8 test.cpp)
[7.3 链地址法解决冲突的思路](#7.3 链地址法解决冲突的思路)
[7.4 链地址法代码实现](#7.4 链地址法代码实现)
[7.4.1 链地址法的哈希表结构](#7.4.1 链地址法的哈希表结构)
[7.4.2 Insert函数的实现](#7.4.2 Insert函数的实现)
[7.2.3 扩容](#7.2.3 扩容)
[7.4.4 Find函数的实现](#7.4.4 Find函数的实现)
[7.4.5 Erase函数的实现](#7.4.5 Erase函数的实现)
[7.2.6 析构函数的实现](#7.2.6 析构函数的实现)
[7.2.7 HashTable.h代码](#7.2.7 HashTable.h代码)
[7.2.8 test.cpp代码](#7.2.8 test.cpp代码)
一、哈希概念
哈希(hash)又称散列,是一种组织数据的方式。从译名来看,有散乱排列的意思。本质就是通过哈希函数把关键字Key跟存储位置建立一个映射关系,查找时通过这个哈希函数计算出Key存储的位置,进行快速查找。
二、直接定址法
当关键字的范围比较集中时,直接定址法就是非常简单高效的方法,比如一组关键字都在[0,99]之间,那么我们开一个100个数的数组,每个关键字的值直接就是存储位置的下标。再比如一组关键字值都在[a,z]的小写字母,那么我们开一个26个数的数组,每个关键字acsii码-aascii码就是存储位置的下标。也就是说直接定址法本质就是用关键字计算出一个绝对位置或者相对位置。这个方法我们在计数排序部分已经用过了,其次在string章节的下面OJ也用过了。
387. 字符串中的第一个唯一字符 - 力扣(LeetCode)
cpp
class Solution {
public:
int firstUniqChar(string s) {
// 每个字⺟的ascii码-'a'的ascii码作为下标映射到count数组,数组中存储出现的次数
int count[26] = {0};
// 统计次数
for(auto ch : s)
{
count[ch-'a']++;
}
for(size_t i = 0; i < s.size(); ++i)
{
if(count[s[i]-'a'] == 1)
return i;
}
return -1;
}
};
三、哈希冲突
直接定址法的缺点也非常明显,当关键字的范围比较分散时,就很浪费内存甚至内存不够用。假设我们只有数据范围是[0,9999]的N个值,我们要映射到一个M个空间的数组中(一般情况M>=N),那么就要借助哈希函数(hash function)hf,关键字key被放到数组的h(key)位置,这里要注意的是h(key)计算出的值必须在[0,M)之间。
这里存在的一个问题就是,两个不同的key可能会映射到同一个位置去,这种问题我们叫做哈希冲突,或者哈希碰撞。理想情况是找出一个好的哈希函数避免冲突,但是实际场景中,冲突是不可避免的,所以我们尽可能设计出优秀的哈希函数,减少冲突的次数,同时也要去设计出解决冲突的方案。
四、负载因子
假设哈希表中已经映射存储了N个值,哈希表的大小为M,那么负载因子N/M,负载因子有些地方也翻译为载荷因子/装载因子等,他的英文为loadfactor。负载因子越大,哈希冲突的概率越高,空间利用率越高;负载因子越小,哈希冲突的概率越低,空间利用率越低;
五、将关键字转为整数
我们将关键字映射到数组中位置,一般是整数好做映射计算,如果不是整数,我们要想办法转换成整数,这个细节我们后面代码实现中再进行细节展示。下面哈希函数部分我们讨论时,如果关键字不是整数,那么我们讨论的Key是关键字转换成的整数。
六、哈希函数
一个好的哈希函数应该让N个关键字被等概率的均匀的散列分布到哈希表的M个空间中,但是实际中却很难做到,但是我们要尽量往这个方向去考量设计。
6.1 除法散列法/除留余数法
- 除法散列法也叫做除留余数法,顾名思义,假设哈希表的大小为M,那么通过key除以M的余数作为映射位置的下标,也就是哈希函数为:h(key)=key % M。
- 当使用除法散列法时,要尽量避免M为某些值,如2的幂,10的幂等。如果是2,那么key%2的X次方本质相当于保留key的后X位,那么后x位相同的值,计算出的哈希值都是一样的,就冲突了。如:{63,31}看起来没有关联的值,如果M是16,也就是2,那么计算出的哈希值都是15,因为63的二进制后8位是 00111111,31的二进制后8位是 00011111。如果是10的X次方,就更明显了,保留的都是10进值的后x位,如:[112,12312},如果M是100,也就是10²,那么计算出的哈希值都是12。
- 当使用除法散列法时,建议M取不太接近2的整数次幂的一个质数(素数)。
- 需要说明的是,实践中也是八仙过海,各显神通,Java的HashMap采用除法散列法时就是2的整数次幂做哈希表的大小M,这样玩的话,就不用取模,而可以直接位运算,相对而言位运算比模更高效一些。但是他不是单纯的去取模,比如M是2^16次方,本质是取后16位,那么用key'=key>>16,然后把key和key'异或的结果作为哈希值。也就是说我们映射出的值还是在[0,M)范围内,但是尽量让key所有的位都参与计算,这样映射出的哈希值更均匀一些即可。所以我们上面建议M取不太接近2的整数次幂的一个质数的理论是大多数数据结构书籍中写的理论吗,但是实践中,灵活运用,抓住本质,而不能死读书。(了解)
6.2 乘法散列法(了解)
- 乘法散列法对哈希表大小M没有要求,他的大思路第一步:用关键字K乘上常数A(0<A<1),并抽取出k*A的小数部分。第二步:后再用M乘以k*A的小数部分,再向下取整。
- h(key)= floor(M x(A ×key)%1.0)),其中floor表示对表达式进行下取整,A∈(0,1),这里最重要的是A的值应该如何设定,Knuth认为A=(
-1)/2=0.6180339887...(黄金分割点)比较好。
- 乘法散列法对哈希表大小M是没有要求的,假设M为1024,key为1234,A=0.6180339887,A*key= 762.6539420558,取小数部分为0.6539420558,M×((AXkey)%1.0) = 0.6539420558*1024=669.6366651392,那么h(1234)=669。
6.3 全域散列法(了解)
- 如果存在一个恶意的对手,他针对我们提供的散列函数,特意构造出一个发生严重冲突的数据集,比如,让所有关键字全部落入同一个位置中。这种情况是可以存在的,只要散列函数是公开且确定的,就可以实现此攻击。解决方法自然是见招拆招,给散列函数增加随机性,攻击者就无法找出确定可以导致最坏情况的数据。这种方法叫做全域散列。
- hab(key)=((a x key +6)%P)%M,P需要选一个足够大的质数,a可以随机选[1,P-1]之间的任意整数,b可以随机选[0,P-1]之间的任意整数,这些函数构成了一个P*(P-1)组全域散列函数组。假设P=17,M=6,a=3,b=4,则h34(8)=((3×8+4)%17)%6=5。
- 需要注意的是每次初始化哈希表时,随机选取全域散列函数组中的一个散列函数使用,后续增删查改都固定使用这个散列函数,否则每次哈希都是随机选一个散列函数,那么插入是一个散列函数,查找又是另一个散列函数,就会导致找不到插入的key了。
6.4 其他方法(了解)
- 上面的几种方法是《算法导论》书籍中讲解的方法。
- 《殷人昆数据结构:用面向对象方法与C++语言描述(第二版)》和《数据结构(C语言版)].严蔚敏_吴伟民》等教材型书籍上面还给出了平方取中法、折叠法、随机数法、数学分析法等,这些方法相对更适用于一些局限的特定场景,有兴趣可以去看看这些书籍。
七、处理哈希冲突
实践中哈希表一般还是选择除法散列法作为哈希函数,当然哈希表无论选择什么哈希函数也避免不了冲突,那么插入数据时,如何解决冲突呢?主要有两种两种方法,开放定址法和链地址法。
7.1 开放定址法
在开放定址法中所有的元素都放到哈希表里,当一个关键字key用哈希函数计算出的位置冲突了,则按照某种规则找到一个没有存储数据的位置进行存储,开放定址法中负载因子一定是小于的。这里的规则有三种:线性探测、二次探测、双重探测。
7.1.1 线性探测
- 从发生冲突的位置开始,依次线性向后探测,直到寻找到下一个没有存储数据的位置为止,如果走到哈希表尾,则回绕到哈希表头的位置。
- h(key)=hash0=key%M,hasho位置冲突了,则线性探测公式为:hc(key,i)=hashi =(hash0+i) % M,i={1,2,3,..,M-1},因为负载因子小于1,则最多探测M-1次,一定能找到一个存储key的位置。
- 线性探测的比较简单且容易实现,线性探测的问题假设,hasho位置连续冲突,hash0,hash1,hash2位置已经存储数据了,后续映射到hash0,hash1,hash2,hash3的值都会争夺hash3位置,这种现象叫做群集/堆积。下面的二次探测可以一定程度改善这个问题。
- 下面演示{19,30,5,36,13,20,21,12}等这一组值映射到M=11的表中。

h(19) = 8 , h(30) = 8 , h(5) = 5 , h(36) = 3 , h(13) = 2 , h(20) = 9 , h(21) = 10, h(12) = 1

7.1.2 二次探测
- 从发生冲突的位置开始,依次左右按二次方跳跃式探测,直到寻找到下一个没有存储数据的位置为止,如果往右走到哈希表尾,则回绕到哈希表头的位置;如果往左走到哈希表头,则回绕到哈希表尾的位置;
- h(key)=hash0=key%M,hash0位置冲突了,则二次探测公式为:he(key,i)=hashi =(hash0±i²)%M,i={1,2,3,...M/2)
- 二次探测当hashi=(hash0-i*i)%M时,当hashi<0时,需要hashi += M
- 下面演示{19,30,52,63,11,22}等这一组值映射到M=11的表中。

h(19) = 8, h(30) = 8, h(52) = 8, h(63) = 8, h(11) = 0, h(22) = 0

7.1.3 双重散列(了解)
- 第一个哈希函数计算出的值发生冲突,使用第二个哈希函数计算出一个跟key相关的偏移量值,不断往后探测,直到寻找到下一个没有存储数据的位置为止。
- h1(key)=hash0=key%M,hash0位置冲突了,则双重探测公式为:hc(key,i)=hashi =(hash0+i* h2(key)) %M,i={1,2,3,..,M}
- 要求h(key)<M且h2(key)和M互为质数,有两种简单的取值方法:1、当M为2整数幂时,h2(key)从[0,M-1]任选一个奇数;2、当M为质数时,h2(key)=key %(M一1)+ 1
- 保证h2(keg)与M互质是因为根据固定的偏移量所寻址的所有位置将形成一个群,若最大公约数p=gcd(M,h1(key)>1,那么所能寻址的位置的个数为M/P<M,使得对于一个关键字来说无法充分利用整个散列表。举例来说,若初始探查位置为1,偏移量为3,整个散列表大小为12,那么所能寻址的位置为{1,4,7,10},寻址个数为12/gcd(12,3)=4
- 下面演示{19,30,52,74}等这一组值映射到M=11的表中,设h(key)=key%10+1

7.2 开放定址法代码实现
开放定址法在实践中,不如下面讲的链地址法,因为开放定址法解决冲突不管使用哪种方法,占用的都是哈希表中的空间,始终存在互相影响的问题。所以开放定址法,我们简单选择线性探测实现即可。
7.2.1 开放定址法的哈希表结构
enum State
{
EXIST,
EMPTY,
DELETE
};
template < class K , class V >
struct HashData
{
pair<K, V> _kv;
State _state = EMPTY;
};
template < class K , class V >
class HashTable
{
private :
vector<HashData<K, V>> _tables;
size_t _n = 0 ; // 表中存储数据个数
};
要注意的是这里需要给每个存储值的位置加一个状态标识,否则删除一些值以后,会影响后面冲突的值的查找。如下图,我们删除30,会导致查找20失败,当我们给每个位置加一个状态标识{EXIST,EMPTY,DELETE},删除30就可以不用删除值,而是把状态改为DELETE,那么查找20时是遇到EMPTY才能停止查找,就可以找到20。
h(19) = 8,h(30)= 8,h(5)= 5,h(36) = 3,h(13) <2,h(20)= 9,h(21)=10,h(12)=1


7.2.2 Insert函数实现
cpp
bool Insert(const pair<K, V>& kv)
{
if (Find(kv.first))
return false;
if (_n * 10 / _tables.size() >= 7) //当负载因子>=0.7就扩容
{
//方式一:
//vector<HashData<K, V>> newtables(_tables.size()*2);
//for (auto& data : _table)
//{
// //旧表数据映射到新表
// if (data._state == EXIST)
// {
// size_t hash0 = data.first % newtables.size();
// //....重新映射
// }
//}
//方式二:
HashTable<K,V> newht;
newht._tables.resize(_tables.size() * 2);
for (auto& data : _tables)
{
//旧表数据映射到新表
if (data._state == EXIST)
{
newht.Insert(data._kv);
}
}
_tables.swap(newht._tables);
}
size_t hash0 = kv.first % _tables.size();
size_t hashi = hash0;
size_t i = 1;
while (_tables[hashi]._state == EXIST)
{
//线性探测
hashi = (hash0 + i)% _tables.size();
++i;
}
_tables[hashi]._kv = kv;
_tables[hashi]._state = EXIST;
++_n;
return true;
}
7.2.3 Find函数实现
cpp
HashData<K, V>* Find(const K& key)
{
size_t hash0 = key % _tables.size();
size_t hashi = hash0;
size_t i = 1;
while (_tables[hashi]._state != EMPTY)
{
if (_tables[hashi]._state==EXIST&&_tables[hashi]._kv.first == key)
{
return &_tables[hashi];
}
hashi = (hash0 + i) % _tables.size();
++i;
}
return nullptr;
}
7.2.4 Erase函数实现
cpp
bool Erase(const K& key)
{
HashData<K, V>* ret = Find(key);
if (ret == nullptr)
{
return false;
}
else
{
ret->_state = DELETE;
return true;
}
}
7.2.5 扩容
这里我们哈希表负载因子控制在0.7,当负载因子到0.7以后我们就需要扩容了,我们是按照2倍扩容,但是同时我们要保持哈希表大小是一个质数,第一个是质数,2倍后就不是质数了。那么如何解决了,一种方案就是上面除法散列中我们讲的JavaHashMap的使用2的整数幂,但是计算时不能直接取模的改进方法。另外一种方案是sgi版本的哈希表使用的方法,给了一个近似2倍的质数表,每次去质数表获取扩容后的大小。如下所示:
cpp
HashTable()
:_tables(__stl_next_prime(0))
,_n(0)
{ }
inline unsigned long __stl_next_prime(unsigned long n)
{
// Note: assumes long is at least 32 bits.
static const int __stl_num_primes = 28;
static const unsigned long __stl_prime_list[__stl_num_primes] =
{
53, 97, 193, 389, 769,
1543, 3079, 6151, 12289, 24593,
49157, 98317, 196613, 393241, 786433,
1572869, 3145739, 6291469, 12582917, 25165843,
50331653, 100663319, 201326611, 402653189, 805306457,
1610612741, 3221225473, 4294967291
};
const unsigned long* first = __stl_prime_list;
const unsigned long* last = __stl_prime_list + __stl_num_primes;
const unsigned long* pos = lower_bound(first, last, n);
return pos == last ? *(last - 1) : *pos;
}
bool Insert(const pair<K, V>& kv)
{
if (Find(kv.first))
return false;
if (_n * 10 / _tables.size() >= 7) //当负载因子>=0.7就扩容
{
//方式一:
//vector<HashData<K, V>> newtables(_tables.size()*2);
//for (auto& data : _table)
//{
// //旧表数据映射到新表
// if (data._state == EXIST)
// {
// size_t hash0 = data.first % newtables.size();
// //....重新映射
// }
//}
//方式二:
HashTable<K,V> newht;
newht._tables.resize(__stl_next_prime(_tables.size()+1));
for (auto& data : _tables)
{
//旧表数据映射到新表
if (data._state == EXIST)
{
newht.Insert(data._kv);
}
}
_tables.swap(newht._tables);
}
size_t hash0 = kv.first % _tables.size();
size_t hashi = hash0;
size_t i = 1;
while (_tables[hashi]._state == EXIST)
{
//线性探测
hashi = (hash0 + i)% _tables.size();
++i;
}
_tables[hashi]._kv = kv;
_tables[hashi]._state = EXIST;
++_n;
return true;
}
7.2.6 Key不能取模的问题
当key是string/Date等类型时,key不能取模,那怎么实现哈希表呢?
7.2.6.1 key是string类型
代码如下所示,当Key是字符串类型的时候:
cpp
int main()
{
const char* a[] = { "abcd","sort","insert" };
HashTable<string, string> ht;
for (auto& e : a)
{
ht.Insert({ e,e });
}
return 0;
}
运行之后会出现错误,这就是因为字符串不能取模的问题而导致的。
所以我们可以增加一层映射,给HashTable增加一个仿函数,这个仿函数支持把key转换成一个可以取模的整形,如果key可以转换为整形并且不容易冲突,那么这个仿函数就用默认参数即可,如果这个Key不能转换为整形,我们就需要自己实现一个仿函数传给这个参数,实现这个仿函数的要求就是尽量key的每值都参与到计算中,让不同的key转换出的整形值不同。将字符串转换成一个size_t类型的数据,然后再进行映射,如下所示:
cpp
#include"HashTable.h"
struct StringHashFunc
{
size_t operator()(const string& s)
{
size_t hash = 0;
for (auto ch : s)
{
hash *= 131;
hash += ch;
}
return hash;
}
};
int main()
{
const char* a[] = { "abcd","sort","insert" };
HashTable<string, string,StringHashFunc> ht;
for (auto& e : a)
{
ht.Insert({ e,e });
}
return 0;
}
如果我们想要用哈希表存放string类型,就需要再创建哈希表的时候,传入一个StringHashFunc的类型,让这个仿函数来将字符串转换成无符号整型,然后再映射。
但是string用来做哈希表的Key的时候非常常见,所以我们可以将HashFunc来特化一下,如下所示:
cpp
template<class K>
struct HashFunc
{
size_t operator()(const K& key)
{
return (size_t)key;
}
};
template<>
struct HashFunc<string>
{
size_t operator()(const string& s)
{
size_t hash=0;
for (auto ch : s)
{
hash *= 131;
hash += ch;
}
return hash;
}
};
7.2.6.2 key是Date类型
当Key是一个Date类型的时候呢?如下所示:
cpp
#include"HashTable.h"
struct Date
{
int _year;
int _month;
int _day;
Date(int year=1,int month=1,int day=1)
:_year(year)
,_month(month)
,_day(day)
{}
};
int main()
{
HashTable<Date, int> ht;
ht.Insert({ {2021,12,1},1 });
ht.Insert({ {2021,12,10},1 });
ht.Insert({ {2021,12,21},1 });
return 0;
}
我们也可以写一个Date类型的仿函数,将Date类型转换成size_t类型的数。如下所示:
cpp
#include"HashTable.h"
struct Date
{
int _year;
int _month;
int _day;
Date(int year=1,int month=1,int day=1)
:_year(year)
,_month(month)
,_day(day)
{}
};
struct DateHashFunc
{
size_t operator()(const Date& d)
{
size_t hash=0;
hash += d._year;
hash *= 131;
hash += d._month;
hash *= 131;
hash += d._day;
hash *= 131;
return hash;
}
};
int main()
{
HashTable<Date, int,DateHashFunc> ht;
ht.Insert({ {2021,12,1},1 });
ht.Insert({ {2021,12,10},1 });
ht.Insert({ {2021,12,21},1 });
return 0;
}
此时运行代码还有一个问题,当我们Find的时候,Key是Date类型,需要判断两个Date类型的变量是否相等,我们再Date类型里面是没有重载==符号的,所以报错了,修改代码如下所示:
cpp
#include"HashTable.h"
struct Date
{
int _year;
int _month;
int _day;
Date(int year=1,int month=1,int day=1)
:_year(year)
,_month(month)
,_day(day)
{}
bool operator==(const Date& d1)
{
return _year == d1._year && _month == d1._month && _day == d1._day;
}
};
struct DateHashFunc
{
size_t operator()(const Date& d)
{
size_t hash=0;
hash += d._year;
hash *= 131;
hash += d._month;
hash *= 131;
hash += d._day;
hash *= 131;
return hash;
}
};
int main()
{
HashTable<Date, int,DateHashFunc> ht;
ht.Insert({ {2021,12,1},1 });
ht.Insert({ {2021,12,10},1 });
ht.Insert({ {2021,12,21},1 });
return 0;
}
7.2.6.3 unordered_map的模板参数的理解
unordered_map的模板参数如下所示:
template < class Key, //unordered_map::key_type class T, //unordered_map::mapped_type class Hash = hash<Key>, // unordered_map::hasher class Pred = equal_to<Key>, /unordered_map::key_equal class Alloc=allocator<pair<const Key,T>>//unordered_map::allocator_type > class unordered_map;
为什么我们需要Hash和Pred这两个这两个模板参数呢?其中Hash是为了将Key转换为无符号整型,Pred是为了来判断两个类型是否相等。
7.2.7 Hashtable.h代码
cpp
#pragma once
#include<iostream>
#include<vector>
#include<string>
using namespace std;
enum State
{
EXIST
, EMPTY
, DELETE
};
template<class K, class V>
struct HashData
{
pair<K, V> _kv;
State _state = EMPTY;
};
template<class K>
struct HashFunc
{
size_t operator()(const K& key)
{
return (size_t)key;
}
};
template<>
struct HashFunc<string>
{
size_t operator()(const string& s)
{
size_t hash=0;
for (auto ch : s)
{
hash *= 131;
hash += ch;
}
return hash;
}
};
template<class K, class V,class Hash=HashFunc<K>>
class HashTable
{
public:
HashTable()
:_tables(__stl_next_prime(0))
, _n(0)
{
}
inline unsigned long __stl_next_prime(unsigned long n)
{
// Note: assumes long is at least 32 bits.
static const int __stl_num_primes = 28;
static const unsigned long __stl_prime_list[__stl_num_primes] =
{
53, 97, 193, 389, 769,
1543, 3079, 6151, 12289, 24593,
49157, 98317, 196613, 393241, 786433,
1572869, 3145739, 6291469, 12582917, 25165843,
50331653, 100663319, 201326611, 402653189, 805306457,
1610612741, 3221225473, 4294967291
};
const unsigned long* first = __stl_prime_list;
const unsigned long* last = __stl_prime_list + __stl_num_primes;
const unsigned long* pos = lower_bound(first, last, n);
return pos == last ? *(last - 1) : *pos;
}
bool Insert(const pair<K, V>& kv)
{
if (Find(kv.first))
return false;
if (_n * 10 / _tables.size() >= 7) //当负载因子>=0.7就扩容
{
//方式一:
//vector<HashData<K, V>> newtables(_tables.size()*2);
//for (auto& data : _table)
//{
// //旧表数据映射到新表
// if (data._state == EXIST)
// {
// size_t hash0 = data.first % newtables.size();
// //....重新映射
// }
//}
//方式二:
HashTable<K, V,Hash> newht;
newht._tables.resize(__stl_next_prime(_tables.size()+1));
for (auto& data : _tables)
{
//旧表数据映射到新表
if (data._state == EXIST)
{
newht.Insert(data._kv);
}
}
_tables.swap(newht._tables);
}
Hash hash;
size_t hash0 = hash(kv.first) % _tables.size();
size_t hashi = hash0;
size_t i = 1;
while (_tables[hashi]._state == EXIST)
{
//线性探测
hashi = (hash0 + i) % _tables.size();
++i;
}
_tables[hashi]._kv = kv;
_tables[hashi]._state = EXIST;
++_n;
return true;
}
HashData<K, V>* Find(const K& key)
{
Hash hash;
size_t hash0 = hash(key) % _tables.size();
size_t hashi = hash0;
size_t i = 1;
while (_tables[hashi]._state != EMPTY)
{
if (_tables[hashi]._state == EXIST && _tables[hashi]._kv.first == key)
{
return &_tables[hashi];
}
hashi = (hash0 + i) % _tables.size();
++i;
}
return nullptr;
}
bool Erase(const K& key)
{
HashData<K, V>* ret = Find(key);
if (ret == nullptr)
{
return false;
}
else
{
ret->_state = DELETE;
return true;
}
}
private:
vector<HashData<K, V>> _tables;
size_t _n;
};
7.2.8 test.cpp
cpp
#include"HashTable.h"
void test1()
{
int a[] = { 19,30,5,36,13,20,21,12 };
HashTable<int, int> ht;
for (auto e : a)
{
ht.Insert({ e,e });
}
ht.Erase(30);
if (ht.Find(20))
{
cout << "找到了" << endl;
}
else
{
cout << "找不到" << endl;
}
if (ht.Find(30))
{
cout << "找到了" << endl;
}
else
{
cout << "找不到" << endl;
}
}
void test2()
{
const char* a[] = { "abcd","sort","insert" };
HashTable<string, string> ht;
for (auto& e : a)
{
ht.Insert({ e,e });
}
}
struct Date
{
int _year;
int _month;
int _day;
Date(int year=1,int month=1,int day=1)
:_year(year)
,_month(month)
,_day(day)
{}
bool operator==(const Date& d1)
{
return _year == d1._year && _month == d1._month && _day == d1._day;
}
};
struct DateHashFunc
{
size_t operator()(const Date& d)
{
size_t hash=0;
hash += d._year;
hash *= 131;
hash += d._month;
hash *= 131;
hash += d._day;
hash *= 131;
return hash;
}
};
int main()
{
HashTable<Date, int,DateHashFunc> ht;
ht.Insert({ {2021,12,1},1 });
ht.Insert({ {2021,12,10},1 });
ht.Insert({ {2021,12,21},1 });
return 0;
}
7.3 链地址法解决冲突的思路
开放定址法中所有的元素都放到哈希表里,链地址法中所有的数据不再直接存储在哈希表中,哈希表中存储一个指针,没有数据映射这个位置时,这个指针为空,有多个数据映射到这个位置时,我们把这些冲突的数据链接成一个链表,挂在哈希表这个位置下面,链地址法也叫做拉链法或者哈希桶。
下面演示{19,30,5,36,13,20,21,12,24,96}等这一组值映射到M=11的表中。

h(19) = 8,h(30) = 8,h(5) = 5,h(36) = 3,h(13) = 2,h(20) = 9,h(21) = 10,h(12) = 1,h(24) = 2,h(96) = 88

扩容
开放定址法负载因子必须小于1,链地址法的负载因子就没有限制了,可以大于1。负载因子越大,哈希冲突的概率越高,空间利用率越高;负载因子越小,哈希冲突的概率越低,空间利用率越低;stl中unordered_xxx的最大负载因子基本控制在1,大于1就扩容,我们下面实现也使用这个方式。
极端场景
如果极端场景下,某个桶特别长怎么办?其实我们可以考虑使用全域散列法,这样就不容易被针对了。但是假设不是被针对了,用了全域散列法,但是偶然情况下,某个桶很长,查找效率很低怎么办?这里在Java8的HashMap中当桶的长度超过一定阀值(8)时就把链表转换成红黑树。一般情况下,不断扩容,单个桶很长的场景还是比较少的,下面我们实现就不搞这么复杂了,这个解决极端场景的思路,大家了解一下。
7.4 链地址法代码实现
7.4.1 链地址法的哈希表结构
cpp
#pragma once
#include<iostream>
#include<vector>
#include<string>
using namespace std;
template<class K,class V>
struct HashNode
{
pair<K, V> _kv;
HashNode<K, V>* _next;
HashNode(const pair<K,V>& kv)
:_kv(kv)
,_next(nullptr)
{ }
};
template<class K>
struct HashFunc
{
size_t operator()(const K& key)
{
return size_t(key)
}
};
template<class K,class V,class Hash=HashFunc<K>>
class HashTable
{
typedef HashNode<K, V> Node;
public:
HashTable()
:_tables(__stl_next_prime(0))
,_n(0)
{ }
inline unsigned long __stl_next_prime(unsigned long n)
{
// Note: assumes long is at least 32 bits.
static const int __stl_num_primes = 28;
static const unsigned long __stl_prime_list[__stl_num_primes] =
{
53, 97, 193, 389, 769,
1543, 3079, 6151, 12289, 24593,
49157, 98317, 196613, 393241, 786433,
1572869, 3145739, 6291469, 12582917, 25165843,
50331653, 100663319, 201326611, 402653189, 805306457,
1610612741, 3221225473, 4294967291
};
const unsigned long* first = __stl_prime_list;
const unsigned long* last = __stl_prime_list + __stl_num_primes;
const unsigned long* pos = lower_bound(first, last, n);
return pos == last ? *(last - 1) : *pos;
}
private:
vector<Node*> _tables; //指针数组
size_t _n; //记录存储的数据个数
};
7.4.2 Insert函数的实现
cpp
bool insert(const pair<K,V>& _kv)
{
Hash hash;
size_t hash0 = hash(_kv.first) % _tables.size();
Node* newnode = new Node(_kv);
newnode->_next = _tables[hash0];
_tables[hash0] = newnode;
_n++;
return true;
}
7.2.3 扩容
开放定址法负载因子必须小于1,链地址法的负载因子就没有限制了,可以大于1。负载因子越大,哈希冲突的概率越高,空间利用率越高;负载因子越小,哈希冲突的概率越低,空间利用率越低;stl中unordered_xxx的最大负载因子基本控制在1,大于1就扩容,我们下面实现也使用这个方式。
cpp
bool insert(const pair<K,V>& _kv)
{
if (_n == _tables.size())
{
//扩容
HashTable<K, V, Hash> newht;
newht._tables.resize(__stl_next_prime(_tables.size() + 1));
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);
}
Hash hash;
size_t hash0 = hash(_kv.first) % _tables.size();
Node* newnode = new Node(_kv);
newnode->_next = _tables[hash0];
_tables[hash0] = newnode;
_n++;
return true;
}
上面这个方法扩容会重新new一个Node结点出来,但是我们原本的_tables里面是有Node结点的,并且两个vector容器交换之后没有释放旧表的空间,我们可以实现下面的方法:
cpp
bool insert(const pair<K,V>& kv)
{
if (Find(kv.first))
{
return false;
}
if (_n == _tables.size())
{
//扩容
vector<Node*> newtable(__stl_next_prime(_tables.size() + 1));
Hash hash;
for (size_t i = 0; i < _tables.size(); i++)
{
Node* cur = _tables[i];
while (cur)
{
Node* next = cur->_next;
size_t hash0 = hash(cur->_kv.first) % newtable.size();
cur->_next = newtable[hash0];
newtable[hash0] = cur;
cur = next;
}
_tables[i] = nullptr;
}
_tables.swap(newtable);
}
Hash hash;
size_t hash0 = hash(kv.first) % _tables.size();
Node* newnode = new Node(kv);
newnode->_next = _tables[hash0];
_tables[hash0] = newnode;
_n++;
return true;
}
上面的这个方法会将原本旧表的Node结点给移动到新表里面,不会再new新的结点出来。
7.4.4 Find函数的实现
cpp
Node* Find(const K& key)
{
Hash hash;
size_t hash0 = hash(key) % _tables.size();
Node* cur = _tables[hash0];
while (cur)
{
if (cur->_kv.first == key)
{
return cur;
}
cur = cur->_next;
}
return nullptr;
}
7.4.5 Erase函数的实现
cpp
bool Erase(const K& key)
{
Hash hash;
size_t hash0 = hash(key) % _tables.size();
Node* cur = _tables[hash0];
Node* prev = nullptr;
while (cur)
{
if (cur->_kv.first == key)
{
if (prev == nullptr)
{
_tables[hash0] = cur->_next;
}
else
{
prev->_next = cur->_next;
}
delete cur;
return true;
}
else
{
prev = cur;
cur = cur->_next;
}
}
return false;
}
7.2.6 析构函数的实现
cpp
~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;
}
}
7.2.7 HashTable.h代码
cpp
#pragma once
#include<iostream>
#include<vector>
#include<string>
using namespace std;
template<class K,class V>
struct HashNode
{
pair<K, V> _kv;
HashNode<K, V>* _next;
HashNode(const pair<K,V>& kv)
:_kv(kv)
,_next(nullptr)
{ }
};
template<class K>
struct HashFunc
{
size_t operator()(const K& key)
{
return size_t(key);
}
};
template<>
struct HashFunc<string>
{
size_t operator()(const string& s)
{
size_t hash = 0;
for (auto ele : s)
{
hash += ele;
hash *= 131;
}
return hash;
}
};
template<class K,class V,class Hash=HashFunc<K>>
class HashTable
{
typedef HashNode<K, V> Node;
public:
HashTable()
:_tables(__stl_next_prime(0))
,_n(0)
{ }
~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;
}
}
inline unsigned long __stl_next_prime(unsigned long n)
{
// Note: assumes long is at least 32 bits.
static const int __stl_num_primes = 28;
static const unsigned long __stl_prime_list[__stl_num_primes] =
{
53, 97, 193, 389, 769,
1543, 3079, 6151, 12289, 24593,
49157, 98317, 196613, 393241, 786433,
1572869, 3145739, 6291469, 12582917, 25165843,
50331653, 100663319, 201326611, 402653189, 805306457,
1610612741, 3221225473, 4294967291
};
const unsigned long* first = __stl_prime_list;
const unsigned long* last = __stl_prime_list + __stl_num_primes;
const unsigned long* pos = lower_bound(first, last, n);
return pos == last ? *(last - 1) : *pos;
}
bool insert(const pair<K,V>& kv)
{
if (Find(kv.first))
{
return false;
}
if (_n == _tables.size())
{
//扩容
vector<Node*> newtable(__stl_next_prime(_tables.size() + 1));
Hash hash;
for (size_t i = 0; i < _tables.size(); i++)
{
Node* cur = _tables[i];
while (cur)
{
Node* next = cur->_next;
size_t hash0 = hash(cur->_kv.first) % newtable.size();
cur->_next = newtable[hash0];
newtable[hash0] = cur;
cur = next;
}
_tables[i] = nullptr;
}
_tables.swap(newtable);
}
Hash hash;
size_t hash0 = hash(kv.first) % _tables.size();
Node* newnode = new Node(kv);
newnode->_next = _tables[hash0];
_tables[hash0] = newnode;
_n++;
return true;
}
Node* Find(const K& key)
{
Hash hash;
size_t hash0 = hash(key) % _tables.size();
Node* cur = _tables[hash0];
while (cur)
{
if (cur->_kv.first == key)
{
return cur;
}
cur = cur->_next;
}
return nullptr;
}
bool Erase(const K& key)
{
Hash hash;
size_t hash0 = hash(key) % _tables.size();
Node* cur = _tables[hash0];
Node* prev = nullptr;
while (cur)
{
if (cur->_kv.first == key)
{
if (prev == nullptr)
{
_tables[hash0] = cur->_next;
}
else
{
prev->_next = cur->_next;
}
delete cur;
_n--;
return true;
}
else
{
prev = cur;
cur = cur->_next;
}
}
return false;
}
private:
vector<Node*> _tables; //指针数组
size_t _n; //记录存储的数据个数
};
7.2.8 test.cpp代码
cpp
#include"HashTable.h"
void test1()
{
int a[] = { -19,-30,5,36,13,20,21,12 };
HashTable<int, int> ht;
for (auto e : a)
{
ht.insert({ e,e });
}
auto ret = ht.Find(-30);
if (ret == nullptr)
{
cout << "找不到" << endl;
}
else
{
cout << "找到了" << endl;
}
ht.Erase(-30);
ret = ht.Find(-30);
if (ret == nullptr)
{
cout << "找不到" << endl;
}
else
{
cout << "找到了" << endl;
}
}
void test2()
{
const char* a[] = { "abcd","sort","left" };
HashTable<string, string> ht;
for (auto ele : a)
{
ht.insert({ ele,ele });
}
}
int main()
{
test2();
return 0;
}