std::hash<Key>::operator()
提供: cppreference.com
std::hash の特殊化は以下のような operator()
を定義するべきです。
Key
型の引数key
を1個取る。key
のハッシュ値を表す std::size_t 型の値を返す。- 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 テンプレートをカスタムクラスに対してどのように特殊化するのかを示します。
Run this code
#include <functional>#include <iostream>#include <string> struct Employee {std::string name;unsignedint ID;}; namespace std {template<>class hash<Employee>{public: size_t operator()(const Employee &employee)const{// computes the hash of an employee using a variant // of the Fowler-Noll-Vo hash function size_t result =2166136261; for(size_t i =0, ie = employee.name.size(); i != ie;++i){ result =(result *16777619)^ 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';}
出力:
177237019