close
名前空間
変種

std::hash<Key>::operator()

提供: cppreference.com
 
 
ユーティリティライブラリ
汎用ユーティリティ
日付と時間
関数オブジェクト
書式化ライブラリ (C++20)
(C++11)
関係演算子 (C++20で非推奨)
整数比較関数
(C++20)
スワップと型操作
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
一般的な語彙の型
(C++11)
(C++17)
(C++17)
(C++17)
(C++17)

初等文字列変換
(C++17)
(C++17)
 
 

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 テンプレートをカスタムクラスに対してどのように特殊化するのかを示します。

#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