std::unordered_setで自作の型を使う

std::unordered_setに自分で定義したクラスを入れたかったので、やってみた。

次のURLが参考になった。

https://stackoverflow.com/questions/15869066/inserting-into-an-unordered-set-with-custom-hash-function

コード

主なポイントは、次の2つだった。

  • 自分で定義したクラスにoperator==()を追加する
  • 自分で定義したクラスのハッシュ値を計算する関数を追加する(便宜上、自分で定義したクラス内で一緒に定義するのがお作法な模様)

なお各所のconstをつけ忘れると、わかりにくいコンパイルエラーに悩まされるので注意。

#include <cstdio>
#include <unordered_set>

class MyClass {
public:
        bool operator==(const MyClass& rhs) const {
                return this->num_ == rhs.num_;
        }

        struct HashFunction {
                size_t operator()(const MyClass& self) const {
                        return self.num_;
                }
        };

private:
        int num_;
};

int main() {
        std::unordered_set<MyClass, MyClass::HashFunction> mySets;
        MyClass obj1;

        mySets.insert(obj1);
        auto it = mySets.find(obj1);
        if(it != mySets.end()) {
                printf("found!\n");
        } else {
                printf("not found...\n");
        }

        return 0;
}

実行結果

できた!

$ ./main
found!