How can I store objects of a class in an unordered_set
? My program needs to frequently check if an object exists in this unordered_set
and if it does,
Since this is the top Google result on Stack Overflow for C++ unordered_set of objects
I'll post a simple yet completely illustrative and copy/paste runnable example:
// UnorderedSetOfObjects.cpp
#include
#include
#include
struct Point
{
int x;
int y;
Point() { }
Point(int x, int y)
{
this->x = x;
this->y = y;
}
bool operator==(const Point& otherPoint) const
{
if (this->x == otherPoint.x && this->y == otherPoint.y) return true;
else return false;
}
struct HashFunction
{
size_t operator()(const Point& point) const
{
size_t xHash = std::hash()(point.x);
size_t yHash = std::hash()(point.y) << 1;
return xHash ^ yHash;
}
};
};
int main(void)
{
std::unordered_set points;
points.insert(Point(1, 1));
points.insert(Point(2, 2));
points.insert(Point(1, 1)); // notice this is a duplicate with the 1st point so it won't change the set
std::cout << "points: " << "\n";
for (auto& point : points)
{
std::cout << "(" << point.x << ", " << point.y << ")" << "\n";
}
return 0;
}