I am trying to define my own hashing function for std::unordered_map and I want to hash a field within a struct which is supposed to be the key. The code below is a simplified version of what I have:
struct TestStruct {
char a[64];
char b[64];
}
struct my_eq {
bool operator()(const TestStruct& test_1, const TestStruct& test_2) const {
return !strcmp(test_1.a, test_2.a) && !strcmp(test_1.b, test_2.b);
}
};
struct my_hash {
unsigned long operator()(const TestStruct& test) const {
return std::hash<std::string_view>(std::string_view(test.a));
}
};
std::unordered_map<TestStruct, int, my_hash,my_eq> map;
The error I get is:
no matching function for call to ‘std::hash<std::basic_string_view<char> >::hash(std::string_view&)
According to the cppreference on std::hash the hash function should support std::string_view. I feel like I'm missing something simple but I cannot figure it out.
std::hash is a class template, not a function template. you need an instance to call it:
return std::hash<std::string_view>()(std::string_view(test.a));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With