Search code examples
c++findconstantsstl-algorithm

C++ find method is not const?


I've written a method that I'd like to declare as const, but the compiler complains. I traced through and found that this part of the method was causing the difficulty:

bool ClassA::MethodA(int x)
{
    bool y = false;
    if(find(myList.begin(), myList.end(), x) != myList.end())
    {
        y = true;
    }
    return y;
}

There is more happening in the method than that, but with everything else stripped away, this was the part that didn't allow the method to be const. Why does the stl find algorithm prevent the method from being const? Does it change the list in any way?


Solution

  • If myList is an object of a custom container type, you could have a problem if its begin() and end() methods don't have a const overload. Also, assuming perhaps the type of x isn't really int in your code, are you sure there's an equality operator that can operate on a const member of that type?