Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No matching call error for unordered_map

Tags:

c++

dictionary

My line:

unordered_map < pair<long long,long long>, long long> myMap;

And the error:

error: no matching function for call to 'std::unordered_map<std::pair<long long int, long long int>, long long int>::unordered_map()'

Code that reproduces the error:

#include <math.h>
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <utility>
using namespace std;

unordered_map < pair<long long,long long>, long long> myMap;

int main() {
    return 0;
}
like image 211
Sean Hill Avatar asked Aug 31 '15 18:08

Sean Hill


1 Answers

std::unordered_map requires a hash functor in order to do anything. By default, that hash functor is is std::hash<Key> - but the standard only provides specializations for the integral types and pointers. std::pair<long long, long long> is neither, so effectively the compiler is telling you that you cannot instantiate the unordered_map you want because its hash functor is ill-formed.

What you need to do is provide your own. For example, here is the worst possible hash functor:

struct AlwaysZero {
    size_t operator()(pair<long long, long long> const& ) const {
        return 0;
    }
};

unordered_map < pair<long long,long long>, long long, AlwaysZero> myMap;

That compiles. It will also perform terribly. You could check out boost::hash_combine to get an idea of how to correctly write a much better hash.

like image 91
Barry Avatar answered Nov 07 '22 22:11

Barry