Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i insert objects into STL set

Tags:

c++

set

stl

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
}
like image 462
Computernerd Avatar asked Nov 09 '13 02:11

Computernerd


People also ask

How do you add elements to a set?

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.

How do you add items to a set in C++?

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.

What are sets in STL?

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.


1 Answers

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;
}
like image 105
Carlos Sanchez Avatar answered Sep 16 '22 20:09

Carlos Sanchez