开发者

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 throug开发者_C百科h 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?


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?


I copied your implementation and had no problems with it:

class ClassA
{
    vector<int> myList;
public:
    bool MethodA(int x) const;
};

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

    return y;
}

When you tried to make the method definition (what you posted above) const, did you remember to change the method declaration as well?


Works fine for me (i686-apple-darwin10-g++-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5646)):

#include <list>
#include <algorithm>

class ClassA
{
public:
  ClassA() { myList.push_back(1); myList.push_back(2); }
  bool MethodA(int x) const;
private:
  std::list<int> myList;
};

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

int main( int argc, char** argv )
{
  ClassA a;
  a.MethodA(5);
  return 0;
}


Post a complete program which fails to compile. This compiles fine:

#include <list>
#include <algorithm>
#include <iostream>

struct Foo {
    std::list<int> ml;
    bool search(int x) const {
        return std::find(ml.begin(), ml.end(), x) != ml.end();
    }
};

int main() {
    const Foo f;
    std::cout << f.search(0) << "\n";
}

Maybe find isn't calling the function you think it is [Edit: more likely, silly me, myList isn't a std::list]. Cutting down to a small program which demonstrates the problem will probably reveal the cause, because at some point you'll remove something and it will start working.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜