std::hash<Key>::operator()
From cppreference.com
std::hash の特殊化は、以下の条件を満たす operator() を定義する必要があります。
Key型の単一の引数 key を取ること。- std::size_t 型の値を返すこと。この値は key のハッシュ値を表します。
- 等しい2つのパラメータ
k1およびk2に対して、std::hash<Key>()(k1) == std::hash<Key>()(k2) であること。 - 等しくない2つの異なるパラメータ
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 { // 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