C++ の std::hash テンプレートクラス
- 
          
            std::hashを使用して、std::stringオブジェクトのハッシュを生成する
- 
          
            std::hashを使用してstd::bitsetオブジェクトのハッシュを生成する
- 
          
            std::hashを使用して、std::vector<bool>オブジェクトのハッシュを生成する
 
この記事では、C++ の STL の std::hash テンプレートクラスを紹介します。
std::hash を使用して、std::string オブジェクトのハッシュを生成する
    
std::hash テンプレートクラスは、STL<functional> ヘッダーの下にあります。ハッシュ関数オブジェクトを作成します。std::hash は DefaultConstructible タイプの要件を満たし、テンプレート引数を指定するだけで済みます。
このテンプレートクラスの複数のデフォルトの特殊化が C++ 標準ライブラリで提供されており、完全なリストはここで見ることができます。指定されたテンプレート引数を使用してハッシュ関数オブジェクトが作成されると、それを利用して、単一の引数を受け入れ、size_t 値を返す operator() を使用して特定のハッシュ値を生成できます。
次の例では、string 特殊化を使用して、任意の文字列に対していくつかのハッシュ値を生成します。
#include <functional>
#include <iomanip>
#include <iostream>
using std::cout;
using std::endl;
using std::setw;
using std::string;
int main() {
  string str1("arbitrary string");
  std::vector<string> vec2 = {"true", "false", "false",
                              "true", "false", "true"};
  std::hash<string> str_hash;
  cout << "hash(str1) - " << str_hash(str1) << endl;
  cout << "hash(vec2 elements) - ";
  for (const auto &item : vec2) {
    cout << str_hash(item) << ", ";
  }
  cout << endl;
  return EXIT_SUCCESS;
}
出力:
hash(str1) - 3484993726433737991
hash(vec2 elements) - 1325321672193711394, 3658472883277130625, 3658472883277130625, 1325321672193711394, 3658472883277130625, 1325321672193711394,
std::hash を使用して std::bitset オブジェクトのハッシュを生成する
STL で提供される std::hash のもう 1つの特殊化は、std::bitset 引数用です。std::bitset は、固定数のビットをシーケンスとして表すクラスであり、ビット操作を簡単にするための複数のメンバー関数を提供することを忘れないでください。
一般に、std::hash スペシャライゼーションで使用されるハッシュ関数は実装に依存するため、これらのオブジェクトをハッシュ問題の普遍的な解決策として使用しないでください。また、これらのハッシュ関数は、プログラムの 1 回の実行内で同じ入力に対して同じ出力を生成するためにのみ必要です。
#include <bitset>
#include <functional>
#include <iomanip>
#include <iostream>
using std::cout;
using std::endl;
using std::setw;
using std::string;
int main() {
  std::bitset<8> b1("00111001");
  std::hash<std::bitset<8>> bitset_hash;
  cout << "hash(bitset<8>) - " << bitset_hash(b1) << endl;
  return EXIT_SUCCESS;
}
出力:
hash(bitset<8>) - 6623666755989985924
std::hash を使用して、std::vector<bool> オブジェクトのハッシュを生成する
次のコードスニペットに示すように、ブール値のベクトルに std::hash 特殊化を使用することもできます。std::hash はユーザー定義クラスに特化することもでき、Boost ライブラリからいくつかの追加の特殊化を利用できることに注意してください(詳細はここにリストされています)。
#include <functional>
#include <iomanip>
#include <iostream>
using std::cout;
using std::endl;
using std::setw;
using std::string;
int main() {
  std::vector<bool> vec1 = {true, false, false, true, false, true};
  std::hash<std::vector<bool> > vec_str_hash;
  cout << "hash(vector<bool>) - " << vec_str_hash(vec1) << endl;
  return EXIT_SUCCESS;
}
出力:
hash(vector<bool>) - 12868445110721718657
