跳转到主内容
新派编程网 - 新潮编程理念,全新技术课堂!

c++怎么自定义哈希函数用于unordered_map_c++ unordered_map自定义哈希函数教程

在C++中使用自定义类型作为unordered_map的键时,需提供哈希函数和相等比较。1. 可通过定义仿函数或lambda实现哈希函数;2. 结构体需重载operator==;3. 哈希设计应减少冲突,推荐组合标准哈希并引入扰动。 在 C++ 中使用
unordered_map
时,如果键的类型不是内置类型(如 int、string),就需要自定义哈希函数。这是因为
unordered_map
内部依赖哈希表实现,需要一个能将键转换为哈希值的函数。1. 自定义哈希函数的基本方式可以通过两种常见方式为
unordered_map
提供自定义哈希函数:定义一个函数对象(仿函数)使用 lambda(需配合构造函数传参)下面以自定义结构体为例说明。2. 示例:用结构体作为 key假设我们有一个表示二维点的结构体
Point
,想把它作为
unordered_map
的键:立即学习“C++免费学习笔记(深入)”;
#include #include struct Point { int x, y; Point(int x, int y) : x(x), y(y) {} // 为了让 unordered_map 正常工作,还需要定义 operator== bool operator==(const Point& other) const { return x == other.x && y == other.y; } }; // 自定义哈希函数对象 struct HashFunction { size_t operator()(const Point& p) const { // 简单哈希:将 x 和 y 混合 return std::hash{}(p.x) ^ (std::hash{}(p.y) << 1); } };
然后就可以这样使用:C函数速查手册(CHM版)C函数速查手册(CHM版)下载
std::unordered_map pointMap; pointMap[Point(1, 2)] = "origin"; pointMap[Point(3, 4)] = "target"; for (const auto& [key, value] : pointMap) { std::cout << "(" << key.x << ", " << key.y << "): " << value << "\n"; }
3. 使用 Lambda 表达式(局部定义)如果你只想在某个作用域内使用自定义哈希,可以用 lambda,但注意不能直接作为模板参数(lambda 类型无法命名),需要借助其他手段,比如:
auto hash = [](const Point& p) { return std::hash{}(p.x) ^ (std::hash{}(p.y) << 1); }; // 需要同时提供相等比较 auto equal = [](const Point& a, const Point& b) { return a.x == b.x && a.y == b.y; }; std::unordered_map map(8, hash, equal);
注意这里必须指定初始桶数(如 8)、哈希函数和等于函数,否则会报错。4. 哈希函数设计建议尽量让不同输入产生不同的哈希值,减少冲突可以组合标准类型的哈希,例如使用
std::hash
避免简单异或,尤其是对称字段(如 x 和 y 互换后哈希相同),可加入位移或乘法扰动推荐写法(更健壮):
size_t operator()(const Point& p) const { size_t h1 = std::hash{}(p.x); size_t h2 = std::hash{}(p.y); return h1 ^ (h2 << 1 | h2 >> (sizeof(size_t)*8-1)); // 引入旋转扰动 }
或者使用官方推荐的哈希组合方法(C++ 标准未提供,但可手动实现):
template void hash_combine(size_t& seed, const T& v) { seed ^= std::hash{}(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } size_t operator()(const Point& p) const { size_t seed = 0; hash_combine(seed, p.x); hash_combine(seed, p.y); return seed; }
这种方式能有效降低哈希碰撞概率。基本上就这些。只要提供哈希函数和相等比较,并重载
operator==
或指定 equals 函数,就能让任意类型作为
unordered_map
的键。

相关文章