如何正确地从无序地图中获取价值?

How to correctly get value from unordered map?

我有这样的无序地图:

static std::unordered_map<std::pair<size_t , size_t>, long> my_map;

然后我想从 my_map:

中获取值
size_t size1 = 1;
size_t size2 = 2;
auto x = make_pair(size1, size2);
auto &result = my_map[x];

但是我有一个错误:

error: no match for ‘operator[]’ (operand types are ‘std::unordered_map<std::pair<long unsigned int, long unsigned int>, long int>’ and ‘std::pair<long unsigned int, long unsigned int>’)
     auto &result = my_map[x];

我该如何克服它?

使用来自的散列函数:

#include <unordered_map>
#include <utility>
#include <map>
#include <functional>
#include <string>

// Only for pairs of std::hash-able types for simplicity.
// You can of course template this struct to allow other hash functions
struct pair_hash {
    template <class T1, class T2>
    std::size_t operator () (const std::pair<T1, T2> &p) const {
        auto h1 = std::hash<T1>{}(p.first);
        auto h2 = std::hash<T2>{}(p.second);

        // Mainly for demonstration purposes, i.e. works but is overly simple
        // In the real world, use sth. like boost.hash_combine
        return h1 ^ h2;
    }
};

int main()
{
    //static std::unordered_map<std::pair<size_t, size_t>, long> my_map;
    static std::unordered_map<std::pair<size_t, size_t>, long, pair_hash> my_map;

    size_t size1 = 1;
    size_t size2 = 2;
    auto x = std::make_pair(size1, size2);
    auto &result = my_map[x];

    return 0;

}