如何将对象插入STL集 [英] How do i insert objects into STL set
本文介绍了如何将对象插入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);
然后,在课堂之外:
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;
}
这篇关于如何将对象插入STL集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文