我想使用 unordered_set
带自定义 struct
.就我而言,自定义 struct
表示欧几里得平面中的二维点。我知道应该定义一个散列函数和比较器运算符,我已经这样做了,正如您在下面的代码中看到的那样:
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 )
return true;
else if (X == other.X && Y == other.Y)
return true;
return false;
};
size_t operator()(const Point& pointToHash) const {
size_t hash = pointToHash.X + 10 * pointToHash.Y;
return hash;
};
};
但是,如果我按如下方式定义集合,则会收到以下错误:
unordered_set<Point> mySet;
Error C2280 'std::hash<_Kty>::hash(const std::hash<_Kty> &)': attempting to reference a deleted function
我错过了什么?
最佳答案
std::unordered_set 的第二个模板参数是用于散列的类型。并将默认为 std::hash<Point>
在你的情况下,它不存在。所以你可以使用 std::unordered_set<Point,Point>
如果哈希器是相同的类型。
或者,如果您不想指定散列器,请定义 std::hash
的特化为 Point
或者摆脱成员函数并在您的特化的主体中实现散列operator()
,或从 std::hash 特化调用成员函数。
#include <unordered_set>
struct Point {
int X;
int Y;
Point() : X(0), Y(0) {};
Point(const int& x, const int& y) : X(x), Y(y) {};
Point(const Point& 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) const {
if (X == other.X && Y == other.Y)
return true;
return false;
};
bool operator<(const Point& other) {
if (X < other.X )
return true;
else if (X == other.X && Y == other.Y)
return true;
return false;
};
// this could be moved in to std::hash<Point>::operator()
size_t operator()(const Point& pointToHash) const noexcept {
size_t hash = pointToHash.X + 10 * pointToHash.Y;
return hash;
};
};
namespace std {
template<> struct hash<Point>
{
std::size_t operator()(const Point& p) const noexcept
{
return p(p);
}
};
}
int main()
{
// no need to specify the hasher if std::hash<Point> exists
std::unordered_set<Point> p;
return 0;
}
Demo
关于c++ - 如何将 unordered_set 与自定义结构一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50888127/