C++ STLのmapやunordered_mapのkeyにstructを使えるようにする

c++

map

operator< を実装する。

#include <iostream>
#include <string>
#include <map>
using namespace std;

struct Item {
    string name;
    int point;
};

bool operator<(const Item& a, const Item& b)
{
    return tie(a.name, a.point) < tie(b.name, b.point);
}

int main() {
    map<Item, bool> M;
    M[{"sambaiz", 1024}] = true;
    cout << M[{"sambaiz", 1024}] << endl;
    return 0;
}

unordered_map

operator== とハッシュ関数を実装する。

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;

struct Item {
    string name;
    int point;
};

bool operator==(const Item& a, const Item& b)
{
    return a.name == a.name && a.point == a.point;
}

struct ItemHash {
    std::size_t operator()(Item item) const
    {
        std::size_t h1 = hash<string>()(item.name);
        std::size_t h2 = hash<int>()(item.point);
        return h1 ^ h2;
    }
};

int main() {
    unordered_map<Item, bool, ItemHash> M;
    M[{"sambaiz", 1024}] = true;
    cout << M[{"sambaiz", 1024}] << endl;
    return 0;
}

参考

優先順位付き大小比較 - Faith and Brave - C++で遊ぼう

Use struct as key to std::unordered_map in C++ – Techie Delight