什么是哈希表:
哈希表的核心思路:借助哈希函数,把范围很大的关键字映射到一段连续的数组下标上,实现平均 (O(1)) 的查找、插入、删除。 我们最常用的方式,就是将哈希计算结果对哈希表桶的总数取模,把映射后的下标限制在合法区间。
当两个不同的 key 算出同一个桶下标,就发生哈希冲突。处理冲突有两种经典方案:拉链法、开放寻址法。
拉链法实现:
#include <iostream>
#include <vector>
#include <list>
#include <utility>
#include <stdexcept>
#include <functional>
using namespace std;
template<typename KeyType, typename ValType>
class HashTableChain
{
private:
int bucket_num;
vector<list<pair<KeyType, ValType>>> buckets;
// 哈希函数:标准哈希值 对桶数量取模
size_t get_index(KeyType key) const
{
return hash<KeyType>{}(key) % bucket_num;
}
public:
// 构造函数,自定义桶数量,默认质数61
explicit HashTableChain(int bucket_size = 61) : bucket_num(bucket_size)
{
buckets.resize(bucket_num);
}
// 插入键值对,允许重复key
void add(KeyType key, ValType val)
{
size_t pos = get_index(key);
buckets[pos].emplace_back(key, val);
}
// 根据key删除元素,成功返回true,不存在返回false
bool remove(KeyType key)
{
size_t pos = get_index(key);
auto &link = buckets[pos];
for(auto it = link.begin(); it != link.end(); ++it)
{
if(it->first == key)
{
link.erase(it);
return true;
}
}
return false;
}
// 查找:存在则把值写入引用参数,返回true
bool search(KeyType key, ValType &res) const
{
size_t pos = get_index(key);
const auto &link = buckets[pos];
for(auto &item : link)
{
if(item.first == key)
{
res = item.second;
return true;
}
}
return false;
}
// 取值,key不存在直接抛异常
ValType get_value(KeyType key) const
{
size_t pos = get_index(key);
const auto &link = buckets[pos];
for(auto &item : link)
{
if(item.first == key)
{
return item.second;
}
}
throw runtime_error("Cannot find this key.");
}
};
// 拉链法测试
void test_chain()
{
HashTableChain<string, int> info_table(61);
info_table.add("小明", 12);
info_table.add("小红", 11);
info_table.add("小宇", 13);
int ans;
if(info_table.search("小明", ans))
{
cout << "小明年龄:" << ans << endl;
}
cout << info_table.get_value("小红") << endl;
info_table.remove("小宇");
}开放寻址法实现(线性探测)
开放寻址法不使用链表,所有数据直接存在数组里面。
发生冲突时,按照固定规则向后寻找下一个空位存放数据。这里选用最简单的线性探测:冲突就尝试 pos+1, pos+2 ...,循环找空位。
要点:开放寻址数组容量要预留充足,一般开到预估元素数量的 2~3 倍,负载因子不能太高,否则探测次数暴涨,速度暴跌。 删除不能直接清空,需要用墓碑标记区分:空位置、被删除位置、有效元素位置。
template<typename KeyType, typename ValType>
class HashTableOpen
{
private:
enum Status{EMPTY, OCCUPIED, TOMBSTONE};
struct Node
{
KeyType key;
ValType val;
Status st = EMPTY;
};
int table_size;
vector<Node> table;
size_t get_index(KeyType key) const
{
return hash<KeyType>{}(key) % table_size;
}
public:
explicit HashTableOpen(int size = 113) : table_size(size)
{
table.resize(table_size);
}
// 插入,线性探测找空位
void add(KeyType key, ValType val)
{
size_t pos = get_index(key);
for(int i = 0; i < table_size; i++)
{
if(table[pos].st == EMPTY || table[pos].st == TOMBSTONE)
{
table[pos].key = key;
table[pos].val = val;
table[pos].st = OCCUPIED;
return;
}
pos = (pos + 1) % table_size;
}
throw runtime_error("Hash table full!");
}
// 查找
bool search(KeyType key, ValType &res) const
{
size_t pos = get_index(key);
for(int i = 0; i < table_size; i++)
{
if(table[pos].st == EMPTY)
return false;
if(table[pos].st == OCCUPIED && table[pos].key == key)
{
res = table[pos].val;
return true;
}
pos = (pos + 1) % table_size;
}
return false;
}
// 删除:打墓碑标记,不能直接清空
bool remove(KeyType key)
{
size_t pos = get_index(key);
for(int i = 0; i < table_size; i++)
{
if(table[pos].st == EMPTY)
return false;
if(table[pos].st == OCCUPIED && table[pos].key == key)
{
table[pos].st = TOMBSTONE;
return true;
}
pos = (pos + 1) % table_size;
}
return false;
}
};
// 开放寻址法测试
void test_open()
{
HashTableOpen<string, int> table(113);
table.add("语文", 85);
table.add("数学", 92);
table.add("英语", 80);
int v;
if(table.search("数学", v))
{
cout << "数学分数:" << v << endl;
}
table.remove("英语");
}
int main()
{
cout << "==== 拉链法测试 ====\n";
test_chain();
cout << "\n==== 开放寻址法测试 ====\n";
test_open();
return 0;
}两种冲突处理方式对比
| 特性 | 拉链法 | 开放寻址法(线性探测) |
|---|---|---|
| 存储结构 | 数组 + 链表 | 单个数组,无链表 |
| 删除操作 | 直接删链表节点,简单 | 不能直接清空,需要墓碑标记,麻烦 |
| 负载因子 | 可以偏高,一般 0.7~1 | 不能太高,建议小于 0.5,否则探测很长 |
| 缓存 | 较差,链表节点分散 | 较好,数据连续放在数组 |
| 适用场景 | CSP 比赛手写哈希首选 | 嵌入式、内存受限场景 |
五、核心坑点总结
- 哈希表容量尽量选质数,减少哈希聚集冲突。
- 拉链法:元素过多,链表变长,复杂度退化至 (O(n))。
- 开放寻址法:一旦负载因子过高,会发生主聚集,连续探测次数爆炸。删除不能直接置空,否则会打断查找链路。
hash<>只支持基础类型、string。自定义结构体当 key,需要自己写哈希函数。- 两种实现都是固定大小,完整版需要扩容逻辑:元素数量超过阈值,新建更大哈希表,全部元素重新哈希搬迁。
六、对比 unordered_map
C++ 标准库unordered_map底层是拉链哈希。比赛中部分测试点专门卡unordered_map,手写拉链哈希表是常用对策。开放寻址在竞赛里用得相对少,主要用来理解冲突处理原理。