我正在尝试使用自定义类作为关键字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) 所述boost::hash_combine模板函数采用一个散列(称为参考seed)和对象v.根据文档,它结合seed了vby 的哈希
seed ^= hash_value(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
Run Code Online (Sandbox Code Playgroud)
我可以看出这是确定性的.我明白为什么要使用XOR.
我敢打赌,这个加法有助于将相似的值广泛分开,因此探测哈希表不会崩溃,但有人可以解释这个神奇常数是什么吗?
以下程序不会编译一组无序的整数对,但它会对整数进行编译.Can unordered_set和它的成员函数可以用在用户定义的类型上,我该如何定义它?
#include <unordered_set>
...
class A{
...
private:
std::unordered_set< std::pair<int, int> > u_edge_;
};
Run Code Online (Sandbox Code Playgroud)
编译错误:
错误:没有匹配函数来调用'std :: unordered_set> :: unordered_set()'
我想使用unordered_set带有自定义的struct。在我的情况下,自定义struct表示欧氏平面中的2D点。我知道应该定义一个哈希函数和比较器运算符,并且我已经做到了,如下面的代码所示:
struct Point {
int X;
int Y;
Point() : X(0), Y(0) {};
Point(const int& x, const int& y) : X(x), Y(y) {};
Point(const IPoint& other){
X = other.X;
Y = other.Y;
};
Point& operator=(const Point& other) {
X = other.X;
Y = other.Y;
return *this;
};
bool operator==(const Point& other) {
if (X == other.X && Y == other.Y)
return true;
return false;
};
bool operator<(const Point& other) {
if (X < other.X …Run Code Online (Sandbox Code Playgroud)