如何将对象插入STL集

Com*_*erd 3 c++ stl set

我试图将一个对象Point2D插入Point2D集但我无法做到,似乎该集适用于int和char但不适用于对象.

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

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
}
Run Code Online (Sandbox Code Playgroud)

Car*_*hez 12

您需要operator<为您的类实现重载.例如,在您的班级中,您可以:

friend bool operator< (const Point2D &left, const Point2D &right);
Run Code Online (Sandbox Code Playgroud)

然后,在课外:

bool operator< (const Point2D &left, const Point2D &right)
{
    return left.x < right.x;
}
Run Code Online (Sandbox Code Playgroud)

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

bool operator< (const Point2D &right) const
{
    return x < right.x;
}
Run Code Online (Sandbox Code Playgroud)

  • 无需将其设为免费功能,只需轻松成为会员即可。这些引用也应该是常量的。 (2认同)