如何将对象插入 STL 集中

2022-01-17 00:00:00 set c++ stl

我正在尝试将对象 Point2D 插入到 Point2D 集中,但我无法做到,似乎该集适用于 int 和 char 但不适用于对象.

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.

我需要帮助才能知道如何将对象插入集合中???假设我想按 x 值的升序对它们进行排序

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
}

推荐答案

您需要为您的类实现 operator< 重载.例如,在你的课堂上,你可以这样做:

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;
}

编辑:根据 Retired Ninja 的建议,您也可以在您的类中将其实现为常规成员函数:

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;
}

相关文章