LoginSignup
0
0

More than 1 year has passed since last update.

cppのunordered_mapのkeyにpairを使う方法

Posted at

概要

cppのunordered_mapのkeyはhashメソッドが内包されている必要がある。

pairにはhashが定義されていないので、独自のhashメソッドを作成して利用する必要がある。

簡易実装として、文字列に変換してstd::hashに用意されているstring methodを使用した。

string res = to_string(p.first) + "^^^" + to_string(p.second);については、uniqueを保証する必要があるため適当な文字列を入れている。

struct HashPair {
    //注意 constがいる
    template<class T1, class T2>
    size_t operator()(const pair<T1, T2> &p) const {
      string res = to_string(p.first) + "^^^" + to_string(p.second);
      return hash<string>()(res);
    }
};
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0