std::hash<Key>::operator()
ja.cppreference.net より
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