唯物是真 @Scaled_Wurm

プログラミング(主にPython2.7)とか機械学習とか

unordered_mapでpairとかを使うときにはhashを定義しないと動かないらしい

unordered_mapにpairを突っ込んだら動かなくて悩んだんですが、自分の作ったクラスだけでなくpairとかtupleでもhashを定義しないと動かないみたいです。

namespace stdに指定する方法とハッシュ関数をunordered_mapに渡す方法の2種類があるみたいですが、とりあえずstdの中に作ってしまう例。

#include <unordered_map>
#include <iostream>

namespace std {
    template <>
    class hash<std::pair<int, int>> {
    public:
        size_t operator()(const std::pair<int, int>& x) const{
            return hash<int>()(x.first) ^ hash<int>()(x.second);
        }
    };
}

int main(void) {
    std::unordered_map<std::pair<int, int>, int> umap;
    umap[std::make_pair(0, 0)] = 0;
    std::cout << umap[std::make_pair(0, 0)] << std::endl;

    return 0;
}

↓のWikipediaの記事を元に書いていますが、hash関数の定義はXORでいいんでしょうか?

それとも素数をかけて足しあわせてmodしたほうがいいんですかね?