C++如何进行哈希计算_C++ STL中std::hash的使用与自定义哈希函数

答案:C++中使用std::hash计算哈希值,支持内置类型并通过特化或自定义函数支持自定义类型,用于unordered_map等容器。

在C++中进行哈希计算通常依赖于标准库提供的 std::hash 模板类,它为许多内置类型(如 int、string、指针等)提供了默认的哈希函数实现。这个功能广泛用于无序容器(如 std::unordered_mapstd::unordered_set)中,以快速定位元素。

std::hash 的基本使用

std::hash 是一个函数对象,调用它会返回对应类型的 size_t 类型哈希值。使用时需包含头文件

示例:

#include iostream>
#include
int main() {
    std::hash<:string> hasher;
    std::string str = "hello";
    size_t hash_val = hasher(str);
    std::cout     return 0;
}

上述代码创建了一个针对字符串的哈希器,并计算出字符串 "hello" 的哈希值。

自定义类型的哈希函数

当你想将自定义类型作为 std::unordered_mapstd::unordered_set 的键时,必须提供对应的哈希函数。有两种常见方式:

  • 特化 std::hash 模板:为自定义类型实现 std::hash 的特化版本。
  • 传入自定义哈希函数对象:在声明无序容器时,显式指定哈希函数类型。

下面以一个简单的结构体为例:

struct Point {
    int x, y;
    bool operator==(const Point& other) const {
        return x == other.x && y == other.y;
    }
};

要让 Point 能用于 unordered_set,需要为其定义哈希函数。可以通过特化 std::hash 实现:

namespace std {
    template struct hash {
        size_t operator()(const Point& p) const {
            // 使用异或和位移组合哈希值
            std::hash int_hasher;
            size_t h1 = int_hasher(p.x);
            size_t h2 = int_hasher(p.y);
            return h1 ^ (h2         }
    };
}

现在可以这样使用:

std::unordered_set points;
points.insert({1, 2});
points.insert({3, 4});

注意:在命名空间 std 中添加模板特化是允许的,但仅限于用户定义类型,且不能修改 std 命名空间中的其他内容。

替代方式:传递自定义哈希函数

如果不希望或不能特化 std::hash,可以在定义容器时传入自定义哈希函数类型:

struct PointHash {
    size_t operator()(const Point& p) const {
        std::hash h;
        return h(p.x) ^ (h(p.y)     }
};

std::unordered_set points;

这种方式更灵活,尤其适用于第三方类型或你无法修改命名空间的情况。

基本上就这些。只要提供可靠的哈希算法,避免过多冲突,就能高效使用 C++ 的哈希容器。