I am trying to insert a object Point2D into a Point2D set but i am not able to do it, it seems the set works for int and char but not for objects.
I need help to know how to insert objects into the set ??? Assuming i want to sort them by ascending order of x value
class Point2D
{
public:
Point2D(int,int);
int getX();
int getY();
void setX(int);
void setY(int);
double getScalarValue();
protected:
int x;
int y;
double distFrOrigin;
void setDistFrOrigin();
};
int main()
{
Point2D abc(2,3);
set<Point2D> P2D;
P2D.insert(abc); // i am getting error here, i don't know why
}
The set::insert is a built-in function in C++ STL which insert elements in the set container or inserts the elements from a position to another position in the set to a different set. Parameters: The function accepts a mandatory parameter element which is to be inserted in the set container.
insert() function is an inbuilt function in C++ STL, which is defined in <set> header file. This function is used to insert elements in the set container. when we insert the element the size of the container is increased by the number of the elements inserted.
Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific sorted order i.e. either ascending or descending.
You need to implement the operator<
overload for your class. For instance, in your class, you can do:
friend bool operator< (const Point2D &left, const Point2D &right);
Then, outside your class:
bool operator< (const Point2D &left, const Point2D &right)
{
return left.x < right.x;
}
Edit: As suggested by Retired Ninja, you can also implement this as a regular member-function within your class:
bool operator< (const Point2D &right) const
{
return x < right.x;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With