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);
然后,在你的课堂之外:
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;
}
这篇关于如何将对象插入 STL 集中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将对象插入 STL 集中


- 从python回调到c++的选项 2022-11-16
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 静态初始化顺序失败 2022-01-01
- C++ 协变模板 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01