使用自定义类型作为键的C+无序映射我试图使用自定义类作为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;
return 0;}我想,我需要告诉C+如何散列类Node然而,我不太清楚该如何做。我如何完成这些任务?
2 回答
UYOU
TA贡献1878条经验 获得超4个赞
控件的比较函数。 unordered_map
单独地,而不是使用相等的比较运算符( operator==
)。例如,如果您想使用后者来比较两个成员的所有成员,这可能是有帮助的。 Node
对象之间,但只有一些特定成员作为 unordered_map
.您也可以使用 而不是定义散列和比较函数。
Node
using h = std::hash<int>;auto hash = [](const Node& n){return ((17 * 31 + h()(n.a)) * 31 + h()(n.b)) * 31 + h()(n.c);}; auto equal = [](const Node& l, const Node& r){return l.a == r.a && l.b == r.b && l.c == r.c;};std: :unordered_map<Node, int, decltype(hash), decltype(equal)> m(8, hash, equal);
我只是在jogoJapan的答案末尾重用了散列方法,但是您可以找到一个更通用的解决方案。 (如果您不想使用Boost)。 我的代码可能太小了。有关可读性稍强的版本,请参见
- 2 回答
- 0 关注
- 422 浏览
添加回答
举报
0/150
提交
取消