Namespaces
Variants

std::hash<Key>::operator()

来自 zh.cppreference.net
 
 
 
 

对于 std::hash 的特化应定义一个 operator(),该函数:

  • 接受一个类型为 key 的单一参数 Key。
  • 返回一个类型为 std::size_t 的值,表示 key 的哈希值。
  • 对于两个相等的参数 k1 和 k2,有 std::hash<Key>()(k1) == std::hash<Key>()(k2)。
  • 对于两个不等的不同参数 k1 和 k2,std::hash<Key>()(k1) == std::hash<Key>()(k2) 的概率应非常小,趋近于 1.0 / std::numeric_limits<size_t>::max()。

参数

key - 待哈希化的对象

返回值

一个表示哈希值的 std:: size_t 类型。

异常

哈希函数不应抛出异常。

示例

以下代码演示了如何为自定义类特化 std::hash 模板。该哈希函数使用 Fowler–Noll–Vo 哈希算法。

#include <cstdint>
#include <functional>
#include <iostream>
#include <string>
struct Employee
{
    std::string name;
    std::uint64_t ID;
};
namespace std
{
    template <>
    class hash<Employee>
    {
    public:
        std::uint64_t operator()(const Employee& employee) const
        {
             // 使用 Fowler-Noll-Vo 哈希算法的变体计算员工对象的哈希值
             // of the Fowler-Noll-Vo hash function
             constexpr std::uint64_t prime{0x100000001B3};
             std::uint64_t result{0xcbf29ce484222325};
             for (std::uint64_t i{}, ie = employee.name.size(); i != ie; ++i)
                 result = (result * prime) ^ employee.name[i];
             return result ^ (employee.ID << 1);
         }
    };
}
int main()
{
    Employee employee;
    employee.name = "Zaphod Beeblebrox";
    employee.ID = 42;
    std::hash<Employee> hash_fn;
    std::cout << hash_fn(employee) << '\n';
}

输出:

12615575401975788567