我正在使用unordered_map
的自定义哈希函数,但我收到此错误:
.../hashtable.h:195:21: error: static assertion failed: hash function must be invocable with an argument of key type
static_assert(__is_invocable<const _H1&, const _Key&>{},
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
hashjoin.cpp:9:12: note: candidate: 'size_t Hasher::operator()(const string&) const'
size_t operator() (string const& key) const {
^~~~~~~~
hashjoin.cpp:9:12: note: no known conversion for argument 1 from 'const int' to 'const string&' {aka 'const std::__cxx11::basic_string<char>&'}
当我使用unordered_multimap
的默认哈希函数时,它工作正常。
我的代码:
#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;
}
答案 0 :(得分:1)
您在unordered_map
中operator()
和Hasher
的密钥中使用了不匹配的类型。
您的代码应该是(请注意内联评论):
#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;
}