How can I use an unordered_set with a custom struct?
The second template parameter to std::unordered_set is the type to use for hashing. and will default to std::hash<Point>
in your case, which doesn't exist. So you can use std::unordered_set<Point,Point>
if the hasher is the same type.
Alternatively if you do not want to specify the hasher, define a specialization of std::hash
for Point
and either get rid of the member function and implement the hashing in the body of your specialization's operator()
, or call the member function from the std::hash specialization.
#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
While the above solution gets you compiling code, avoid that hash function for points. There's a one dimensional subspace parameterized by b
for which all points on the line y = -x/10 + b
will have the same hash value. You'd be better off with a 64 bit hash where the top 32 bits are the x coord and the low 32 bits are the y coord (for example). That'd look like
uint64_t hash(Point const & p) const noexcept
{
return ((uint64_t)p.X)<<32 | (uint64_t)p.Y;
}