在C++中使用自定义类型作为unordered_map的键时,需提供哈希函数和相等比较。1. 可通过定义仿函数或lambda实现哈希函数;2. 结构体需重载operator==;3. 哈希设计应减少冲突,推荐组合标准哈希并引入扰动。

在 C++ 中使用 unordered_map 时,如果键的类型不是内置类型(如 int、string),就需要自定义哈希函数。这是因为 unordered_map 内部依赖哈希表实现,需要一个能将键转换为哈希值的函数。
可以通过两种常见方式为 unordered_map 提供自定义哈希函数:
下面以自定义结构体为例说明。
假设我们有一个表示二维点的结构体 Point,想把它作为 unordered_map 的键:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <unordered_map>
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<int>{}(p.x) ^ (std::hash<int>{}(p.y) << 1);
}
};
然后就可以这样使用:
std::unordered_map<Point, std::string, HashFunction> 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";
}
如果你只想在某个作用域内使用自定义哈希,可以用 lambda,但注意不能直接作为模板参数(lambda 类型无法命名),需要借助其他手段,比如:
auto hash = [](const Point& p) {
return std::hash<int>{}(p.x) ^ (std::hash<int>{}(p.y) << 1);
};
// 需要同时提供相等比较
auto equal = [](const Point& a, const Point& b) {
return a.x == b.x && a.y == b.y;
};
std::unordered_map<Point, std::string, decltype(hash), decltype(equal)> map(8, hash, equal);
注意这里必须指定初始桶数(如 8)、哈希函数和等于函数,否则会报错。
std::hash<T>
size_t operator()(const Point& p) const {
size_t h1 = std::hash<int>{}(p.x);
size_t h2 = std::hash<int>{}(p.y);
return h1 ^ (h2 << 1 | h2 >> (sizeof(size_t)*8-1)); // 引入旋转扰动
}
或者使用官方推荐的哈希组合方法(C++ 标准未提供,但可手动实现):
template<class T>
void hash_combine(size_t& seed, const T& v) {
seed ^= std::hash<T>{}(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 的键。
以上就是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号