c++functionvector

Can't use a C++ const vector passed to a function for find()


Here's a class with some data and an overloaded equality operator:

class Point {
    int x, y;
    
    public:
        Point(int x0, int y0): x(x0), y(y0) {};
        bool operator==(const Point& rval) {
            return x == rval.x && y == rval.y;  
        }
};

And here's a function that successfully takes a vector of such objects, and reports on whether a given object is contained within:

bool hasVal(std::vector<Point>& vec, const Point& target) {
    return find(vec.begin(), vec.end(), target) != vec.end();
}

Now, I would think (and desire) that I could make the vector reference argument const, as it doesn't intend to modify the vector or its contents in any way. However, tagging the vector reference const causes a compiler error:

241 17 C:\Program Files (x86)\Embarcadero\Dev-Cpp\TDM-GCC-64\lib\gcc\x86_64-w64-mingw32\9.2.0\include\c++\bits\predefined_ops.h [Error] no match for 'operator==' (operand types are 'const Point' and 'const Point')

Related: A similar problem arises if I make a class with such a vector as a member, and try to do the same job in a member function tagged const.

(Side note: Making a vector argument like that const seems to work fine for a vector of primtives like int, but not for this programmer-defined object type.)

What's the problem here, and how can I best resolve it?


Solution

  • Your operator== is not marked as a const method and therefore cannot be applied on const elements in vec if it is passed by const&.

    If you change it to the following it will work:

    //---------------------------------vvvvv--
    bool operator==(const Point& rval) const {
        return x == rval.x && y == rval.y;  
    }
    

    Live demo

    Note that good practice dictates marking the operator as a const method anyway (regardless of your issue with std::find), since it does not modify the object.

    See more info about marking methods as const here: What is the meaning of 'const' at the end of a member function declaration?.