使用自定義類型作為鍵的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 關注
- 470 瀏覽
添加回答
舉報
0/150
提交
取消
