C++ find 方法不是const?

Rac*_*hel 5 c++ constants find stl-algorithm

我写了一个我想声明为 const 的方法,但编译器抱怨。我追查了一下,发现是方法的这部分造成了困难:

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

方法中发生的事情比这更多,但是在剥离所有其他内容后,这部分不允许该方法为 const。为什么stl find算法会阻止方法成为const?它是否以任何方式更改列表?

Mik*_*ale 5

如果 myList 是自定义容器类型的对象,并且其 begin() 和 end() 方法没有 const 重载,则可能会出现问题。另外,假设您的代码中 x 的类型可能不是真正的 int ,您确定有一个相等运算符可以对该类型的 const 成员进行操作吗?