要使用自定义类型作为unordered_map的键,需定义哈希函数对象并重载operator==。1. 自定义结构体需实现==运算符用于比较;2. 定义仿函数重载operator()返回size_t,可结合std::hash与推荐的哈希混合方式(如0x9e3779b9异或移位)提升均匀性;3. 模板参数传入自定义哈希类型,不可用lambda但可用仿函数。示例中Point结构体通过PointHash实现键功能,确保哈希唯一性与相等比较正确性。

在C++中,unordered_map 使用哈希表实现,其键类型需要能够被哈希函数处理。标准库为常见类型(如 int、string)提供了默认哈希函数,但如果你使用自定义类型(如结构体或类)作为键,就需要提供自己的哈希函数。
要让自定义类型用于 unordered_map,你需要做两件事:
假设你想用一个表示二维点的结构体作为键:
#include <iostream>
#include <unordered_map>
#include <string>
struct Point {
int x, y;
Point(int x, int y) : x(x), y(y) {}
// 必须定义 operator== 用于比较
bool operator==(const Point& other) const {
return x == other.x && y == other.y;
}
};
// 自定义哈希函数对象
struct PointHash {
size_t operator()(const Point& p) const {
// 简单哈希:将 x 和 y 混合
return std::hash<int>{}(p.x) ^ (std::hash<int>{}(p.y) << 1);
}
};
int main() {
std::unordered_map<Point, std::string, PointHash> pointMap;
pointMap[Point(1, 2)] = "Point A";
pointMap[Point(3, 4)] = "Point B";
for (const auto& [point, label] : pointMap) {
std::cout << "Key: (" << point.x << ", " << point.y
<< ") Value: " << label << "\n";
}
return 0;
}
不能直接传 lambda 给 unordered_map 模板参数,因为模板需要类型,而 lambda 类型是唯一的且无法写出。但你可以使用函数对象或 std::function 包装,不过更推荐仿函数方式。
立即学习“C++免费学习笔记(深入)”;
上面用 ^ 和位移组合哈希值简单但不够均匀。推荐使用更健壮的方法:
struct PointHash {
size_t operator()(const Point& p) const {
size_t hx = std::hash<int>{}(p.x);
size_t hy = std::hash<int>{}(p.y);
// 推荐的哈希合并方式
return hx ^ (hy + 0x9e3779b9 + (hx << 6) + (hx >> 2));
}
};
或者参考 Boost 的哈希组合方式,避免冲突。
基本上就这些。定义好 == 和哈希仿函数,就可以把自定义类型用作 unordered_map 的键了。不复杂但容易忽略细节。以上就是c++++如何自定义哈希函数用于unordered_map_c++ unordered_map自定义哈希示例的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号