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;
unsigned int 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