C++使用“count”时,映射自定义哈希函数会出现编译错误功能
我尝试制作一个自定义哈希函数,它将原始字符串转换为“每个字母表在给定字符串中出现的次数”。它是这样的:
struct hash_nums {
string operator()(const string& s) const {
vector<int> arr(26, 0);
for (char c : s) {
++arr[c-'a'];
}
string str(arr.begin(), arr.end());
return str;
}
};
在主函数中,我编写了这样的代码:
unordered_map<string, vector<string>, hash_nums> um;
...
for (string s : strings)
if (um.count(s)) // do something
但是当我使用 um.count(s) 时,它给了我这个错误:
Line 32: Char 20: note: in instantiation of member function 'std::unordered_map<std::__cxx11::basic_string<char>, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char>>>, Solution::hash_nums, std::equal_to<std::__cxx11::basic_string<char>>, std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char>>>>>>::count' requested here
if (um.count(s)) {
^
我为 std::pair 使用了自定义哈希函数,并且它没有给我这些错误。 另外,仅声明 unordered_map 就可以编译。
出了什么问题?
I tried to make a custom hash function, which transforms original string to "the number of times each alphabet appears in a given string". It goes like this :
struct hash_nums {
string operator()(const string& s) const {
vector<int> arr(26, 0);
for (char c : s) {
++arr[c-'a'];
}
string str(arr.begin(), arr.end());
return str;
}
};
and in main function, I wrote code like this :
unordered_map<string, vector<string>, hash_nums> um;
...
for (string s : strings)
if (um.count(s)) // do something
but when I use um.count(s)
, it gives me this error :
Line 32: Char 20: note: in instantiation of member function 'std::unordered_map<std::__cxx11::basic_string<char>, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char>>>, Solution::hash_nums, std::equal_to<std::__cxx11::basic_string<char>>, std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char>>>>>>::count' requested here
if (um.count(s)) {
^
I used custom hash function for std::pair, and it didn't give me these errors.
Also, only declaring unordered_map compiles just fine.
What has gone wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论