命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | utility‎ | hash
 
 
 
std::hash
hash::operator()
 

std::hash 的特化应当定义一个 operator(),它

  • 接受一个类型为 Key 的单参数 key
  • 返回一个 std::size_t 类型的值,它表示 key 的哈希值。
  • 对于两个相等的参数 k1k2std::hash<Key>()(k1) == std::hash<Key>()(k2)
  • 对于两个不相等的参数 k1k2std::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
        {
             // computes the hash of an employee using a variant
             // 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