如果我有课
class Point
{
public:
Point() {}
Point(int _col, int _row) : row(_row), col(_col) {}
int row, col;
};
如何使用 std::find() 检查点是否已经在 vector 中?我必须重载 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
中,但没有一个解释它是比较对象的指针还是比较对象的实际值对象。
C++ 标准(草案 N3242)说(在第 25.2.5 [alg.find] 部分)std::find
:
Returns: The first iterator i
in the range [first,last)
for which the following corresponding conditions hold: *i == value
[...]. Returns last
if no such iterator is found.
关于它是根据对象的值还是地址进行搜索的问题取决于 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 .