Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 801
Rachel Avatar asked Mar 19 '10 00:03

Rachel


1 Answers

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?

like image 172
Mike Dinsdale Avatar answered Sep 30 '22 00:09

Mike Dinsdale