如果我有课
class Point
{
public:
Point() {}
Point(int _col, int _row) : row(_row), col(_col) {}
int row, col;
};
如何使用std :: find()来检查该点是否已经在向量中?我是否必须重载operator ==?
我正在尝试这样做
#include <algorithm>
if(std::find(v.begin(), v.end(), x) != v.end()) {
/* v contains x */
} else {
/* v does not contain x */
}
我在Stack Overflow上找到的几乎所有答案都建议使用find检查对象是否在std::vector
中,但没有一个解释它是否比较了对象的指针或对象的实际值。
答案 0 :(得分:3)
C ++标准(草案N3242)(在第25.2.5节[alg.find]中)说std::find
:
返回:
i
范围内的第一个迭代器[first,last)
,其中包含以下相应条件:*i == value
[...]。如果没有找到这样的迭代器,则返回last
。
您是否将根据对象的值或地址进行搜索的问题取决于operator==
的实现方式。简单的答案是:std::find
将返回一个迭代器到operator==
返回true的对象。
通常,这只是一个基于值的比较(因为通常会实现operator==
来比较两个对象的值),因此您通常应该期望std::find
搜索范围您提供的价值(不是您提供的对象的地址)。
operator==
可以实现compares based on address,如下所示:
bool operator==(const Point& left, const Point& right) {
return &left == &right;
}
使用此operator==
会比较地址,因此std::find
将搜索与您提供的地址具有相同地址的对象。但是,这样实现operator==
通常是一个坏主意。大多数人会这样实现operator==
:
bool operator==(const Point& left, const Point& right) {
return left.row == right.row && left.col == right.col;
}
,当与std::find
一起使用时,compare Point
s based on their values。
答案 1 :(得分:0)
除非你的类型是 PODs 基本类型,否则你需要提供一个相等的函数,成员与否。
std::find
有两个基本版本,一个假定一个相等运算符,另一个使用你提供的相等函数。
我建议您将operator==
和operator<
添加到要进行相等或有序比较的任何类中。
这是您班级的更新版本:
class Point
{
int x; // These are private by default.
int y;
public:
Point(int new_x, int new_y) : x(new_x), y(new_y)
{ ; }
bool operator==(const Point& p) const
{
return (x == p.x) && (y == p.y);
}
};
成员方法operator==
允许进行比较,而不会将值公开给朋友或公众。
如果您想使用独立式比较功能,您需要将值设为公开或使该功能成为朋友:
class Point
{
int x; // These are private by default.
int y;
public:
Point(int new_x, int new_y) : x(new_x), y(new_y)
{ ; }
friend bool operator==(const Point& a, const Point& b);
};
bool operator==(const Point& a, const Point& b)
{
return (a.x == b.x) && (a.y == b.y);
}
如果您想使用std::find
的独立功能,示例如下:
std::vector<Point> point_container;
//...
Point p;
std::vector<Point>::const_iterator iter;
iter = std::find(point_container.begin(), point_container.end(),
p,
Equal_Points);
Equal_Points
是一个独立的功能,可以比较两个点的成员。