我正在尝试使用自定义类作为关键字unordered_map
,如下所示:
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
class node;
class Solution;
class Node {
public:
int a;
int b;
int c;
Node(){}
Node(vector<int> v) {
sort(v.begin(), v.end());
a = v[0];
b = v[1];
c = v[2];
}
bool operator==(Node i) {
if ( i.a==this->a && i.b==this->b &&i.c==this->c ) {
return true;
} else {
return false;
}
}
};
int main() {
unordered_map<Node, int> m;
vector<int> v;
v.push_back(3);
v.push_back(8);
v.push_back(9);
Node n(v);
m[n] = 0; …
Run Code Online (Sandbox Code Playgroud) 我想将POD结构用作地图中的哈希键,例如
struct A { int x; int y; };
std::unordered_map<A, int> my_map;
Run Code Online (Sandbox Code Playgroud)
但我不能这样做,因为没有哈希函数可自动为此类结构生成。
我正在尝试创建以下 unordered_map:
std::unordered_map<CString, CString, std::function<size_t(const CString &data)>> usetResponse(100, [](const CString &data)
{
return std::hash<std::string>()((LPCSTR)data);
});
Run Code Online (Sandbox Code Playgroud)
我为 CString 提供了哈希函数,但编译器仍然返回错误:
error C2338: The C++ Standard doesn't provide a hash for this type.
error C2664: 'std::unordered_map<CString,CString,std::hash<_Kty>,std::equal_to<_Kty>,std::allocator<std::pair<const
_Kty,_Ty>>>::unordered_map(std::initializer_list<std::pair<const _Kty,_Ty>>,unsigned int,const std::hash<_Kty> &,const _Keyeq &,const std::allocator<std::pair<const _Kty,_Ty>> &)' : cannot convert argument 1 from 'std::unordered_map<CString,CString,std::function<size_t (const CString &)>,std::equal_to<_Kty>,std::allocator<std::pair<const
_Kty,_Ty>>>' to 'const std::unordered_map<CString,CString,std::hash<_Kty>,std::equal_to<_Kty>,std::allocator<std::pair<const
_Kty,_Ty>>> &'
Run Code Online (Sandbox Code Playgroud)
请告诉我我做错了什么?