使用自定义类型作为unordered_map键时需提供哈希函数,可通过特化std::hash或传入哈希函数对象实现,推荐结合质数或标准库方法混合哈希值以减少冲突,确保相等对象哈希值相同且分布均匀。

在 C++ 中使用 unordered_map 时,如果键类型不是内置类型(如 int、string),就需要自定义哈希函数。否则编译器会报错:找不到合适的哈希特化版本。
要让自定义类型作为 unordered_map 的键,有两种主要方式:
1. 提供 std::hash 的特化版本
如果你的类型是结构体或类,可以在 std:: 命名空间中为它特化 std::hash:
立即学习“C++免费学习笔记(深入)”;
#include <unordered_map>
#include <functional>
<p>struct Point {
int x, y;
bool operator==(const Point& other) const {
return x == other.x && y == other.y;
}
};</p><p>namespace std {
template<>
struct hash<Point> {
size_t operator()(const Point& p) const {
return hash<int>{}(p.x) ^ (hash<int>{}(p.y) << 1);
}
};
}
2. 传入自定义哈希函数对象
不修改 std 命名空间,而是通过模板参数传入哈希函数和相等比较:
struct PointHash {
size_t operator()(const Point& p) const {
return hash<int>{}(p.x) ^ (hash<int>{}(p.y) << 1);
}
};
<p>unordered_map<Point, string, PointHash> myMap;
简单的异或可能导致冲突增多,比如 (1,2) 和 (2,1) 可能产生相同哈希值。改进方式:
template<typename T, typename U>
size_t hash_combine(const T& a, const U& b) {
size_t seed = hash<T>{}(a);
seed ^= hash<U>{}(b) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
return seed;
}
<p>// 使用
return hash_combine(p.x, p.y);
对于 pair<int,int> 这种常用但无默认哈希的类型,可以这样写:
struct PairHash {
template <class T1, class T2>
size_t operator() (const pair<T1,T2>& p) const {
auto h1 = hash<T1>{}(p.first);
auto h2 = hash<T2>{}(p.second);
return h1 ^ (h2 << 1);
}
};
<p>unordered_map<pair<int, int>, int, PairHash> coordMap;
编写自定义哈希时注意以下几点:
boost::hash_combine 思路提升质量基本上就这些。只要实现好哈希函数和 == 操作符,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号