要使用自定义类型作为unordered_map的键,需提供哈希函数和相等比较:1. 可特化std::hash模板,如为Point定义hash;2. 或传入lambda/函数对象作为哈希和比较函数,需指定桶数量;3. 推荐用质数扰动(如0x9e3779b9)与异或组合哈希值以减少冲突;4. 对pair可写通用PairHash结构体。确保相同对象哈希一致,不同对象尽量避免碰撞,提升性能。

在C++中使用unordered_map时,如果键类型是自定义类型(如pair<int, int>、结构体等),编译器无法自动提供哈希函数,需要手动实现自定义哈希函数。以下是几种常见且实用的实现技巧。
要让unordered_map支持自定义类型,可以特化std::hash模板。以二维坐标点Point为例:
struct Point {
    int x, y;
    bool operator==(const Point& other) const {
        return x == other.x && y == other.y;
    }
};
namespace std {
    template<>
    struct hash<Point> {
        size_t operator()(const Point& p) const {
            // 使用异或和质数扰动减少冲突
            return hash<int>{}(p.x) ^ (hash<int>{}(p.y) << 1);
        }
    };
}
注意:虽然可以在std命名空间中特化std::hash,但仅限于用户定义类型。不建议对基础类型或标准容器进行特化。
如果不希望修改std::hash,可以在声明unordered_map时传入自定义哈希函数和相等比较函数:
立即学习“C++免费学习笔记(深入)”;
auto hash_func = [](const Point& p) {
    return hash<int>{}(p.x) ^ (hash<int>{}(p.y) << 1);
};
auto equal_func = [](const Point& a, const Point& b) {
    return a.x == b.x && a.y == b.y;
};
unordered_map<Point, string, decltype(hash_func), decltype(equal_func)> my_map(8, hash_func, equal_func);
这里需要指定初始桶数量(如8)并传入函数对象,否则编译器无法推导。
对于多个字段组合哈希值,推荐使用更均匀的方法避免冲突。例如使用质数乘法和异或:
struct PointHash {
    size_t operator()(const Point& p) const {
        size_t h1 = hash<int>{}(p.x);
        size_t h2 = hash<int>{}(p.y);
        // 使用FNV-like方法或质数扰动
        return h1 ^ (h2 + 0x9e3779b9 + (h1 << 6) + (h1 >> 2));
    }
};
其中0x9e3779b9是黄金比例常数,有助于分散哈希值。
虽然std::pair没有默认哈希,可以这样写一个通用哈希组合器:
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);
    }
};
unordered_map<pair<int, int>, int, PairHash> coord_map;
基本上就这些。关键是保证相同对象产生相同哈希值,不同对象尽量避免冲突。结合^、位移、质数扰动能有效提升性能。
以上就是c++++怎么自定义哈希函数用于unordered_map_c++自定义hash函数实现技巧的详细内容,更多请关注php中文网其它相关文章!
                        
                        c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号