std::find 它是如何工作的?运算符== [英] std::find how does it work? operator==

查看:30
本文介绍了std::find 它是如何工作的?运算符==的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有课

class Point
{
public:
  Point() {}
  Point(int _col, int _row) : row(_row), col(_col) {}
  int row, col;
};

如何使用 std::find() 检查点是否已经在向量中?我必须重载 operator== 吗?

how can I use std::find() to check whether the point is already in vector? DO I have to overload 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 中,但没有一个解释它是比较对象的指针还是比较对象的实际值对象.

Almost every answer I find on Stack Overflow suggest using find to check whether the object is in std::vector but none of them explains whether it compares the pointer of objects or the actual values of the object.

推荐答案

C++ 标准(草案 N3242)说(在第 25.2.5 节 [alg.find] 中)std::find:

The C++ standard (draft N3242) says (in section 25.2.5 [alg.find]) that std::find:

返回:[first,last)范围内的第一个迭代器i,满足以下相应条件:*i == 值[...].如果找不到这样的迭代器,则返回 last.

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 的对象返回一个迭代器.

Your question of whether it will search based on the value or the address of the object depends on how operator== is implemented. The simple answer is: std::find will return an iterator to the object for which operator== returned true.

通常,这只是基于值的比较(因为 operator== 通常用于比较两个对象的值),因此您通常应该期待 std::find 以搜索您提供的值的范围(不是您提供的对象的地址).

Usually, this will just be a value-based comparison (because operator== is usually implemented to compare the values of two objects), and so you should generally expect std::find to search the range for the value you've provided (not the address of the object you provided).

operator== 可以实现为基于地址进行比较,像这样:

It's possible for operator== to be implemented such that it compares based on address, like so:

bool operator==(const Point& left, const Point& right) {
    return &left == &right;
}

使用此 operator== 将比较地址,因此 std::find 将搜索与您提供的地址具有相同地址的对象.但是,像这样实现 operator== 通常是一个坏主意.大多数人会像这样实现 operator==:

Using this operator== will compare addresses, and so std::find will search for an object that has the same address as the one you've provided. It's generally a bad idea to implement operator== like this, though. Most people would implement operator== like so:

bool operator==(const Point& left, const Point& right) {
    return left.row == right.row && left.col == right.col;
}

当与std::find一起使用时,将比较Point s 基于它们的值.

which, when used with std::find, will compare Points based on their values.

这篇关于std::find 它是如何工作的?运算符==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆