std:: hash<Key>:: operator()
From cppreference.net
C++
Utilities library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
std::hash
|
hash::operator()
|
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