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

时间:2016-10-18 20:09:28

标签: c++ 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];

我怎样才能克服它?

1 个答案:

答案 0 :(得分:0)

使用here中的哈希函数:

#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;

}