Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::find how does it work? operator== [duplicate]

Tags:

c++

vector

If I have a class

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

how can I use std::find() to check whether the point is already in vector? DO I have to overload operator== ?

I am trying to do this

#include <algorithm>

if(std::find(v.begin(), v.end(), x) != v.end()) {
    /* v contains x */
} else {
    /* v does not contain x */
}

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.

like image 829
Bhavik Shah Avatar asked Feb 17 '26 22:02

Bhavik Shah


1 Answers

The C++ standard (draft N3242) says (in section 25.2.5 [alg.find]) that 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.

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.

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).

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;
}

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;
}

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

like image 186
Cornstalks Avatar answered Feb 19 '26 13:02

Cornstalks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!