名稱空間
變體
操作

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

來自 cppreference.com
< 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