kotokbek kotokbek - 1 month ago 13
C++ Question

How to correctly get value from unordered map?

I have such unordered map:

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


Then I want to get value from
my_map
:

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


But I have an error:

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


How can I overcome it?

Answer

Using the hash function from 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;

}
Comments