std::find how does it work? operator==

前端 未结 2 574
夕颜
夕颜 2021-01-22 00:34

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

2条回答
  •  难免孤独
    2021-01-22 00:57

    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.

提交回复
热议问题