Reputation: 991
I'm using a custom hash function with unordered_map
, but I get this error:
error: static assertion failed: hash function must be invocable with an argument of key type
It works fine when I use the default hash function of unordered_multimap
.
My code:
#include<vector>
#include<string>
#include<unordered_map>
using namespace std;
class Hasher {
public:
size_t operator() (string const& key) const {
size_t hash = 0;
for(size_t i = 0; i < key.size(); i++) {
hash += key[i] % 7;
}
return hash;
}
};
int main(int argc, char const *argv[]) {
unordered_multimap<int, int, Hasher, equal_to<int>> hashmap;
hashmap.insert(make_pair(1, 11));
hashmap.insert(make_pair(1, 21));
hashmap.insert(make_pair(2, 12));
hashmap.insert(make_pair(3, 13));
auto range = hashmap.equal_range(1);
return 0;
}
Upvotes: 1
Views: 17249
Reputation: 3651
You are using mismatched types in the key of unordered_map
and operator()
in Hasher
.
You code should be (please note the comments inline):
#include<vector>
#include<string>
#include<unordered_map>
using namespace std;
class Hasher {
public:
size_t operator() (string const& key) const { // the parameter type should be the same as the type of key of unordered_map
size_t hash = 0;
for(size_t i = 0; i < key.size(); i++) {
hash += key[i] % 7;
}
return hash;
}
};
int main(int argc, char const *argv[]) {
unordered_multimap<std::string, int, Hasher, equal_to<std::string>> hashmap; // key should be string type
hashmap.insert(make_pair("1", 11)); // key should be string type
hashmap.insert(make_pair("1", 21));
hashmap.insert(make_pair("2", 12));
hashmap.insert(make_pair("3", 13));
auto range = hashmap.equal_range("1"); // equal_range's parameter should be the same type as key
return 0;
}
Upvotes: 8