C ++ search method not const?

I wrote a method that I would like to declare as const, but the compiler complains. I followed and found that this part of the method is causing difficulties:

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

The method has more than in this case, but with everything else that was deleted, this was the part that did not allow the method to be const. Why does the stl search algorithm prevent the method from being const? Does this list change in any way?

+4
source share
4 answers

If myList is an object of a custom container type, a problem may arise if its begin () and end () methods do not have a const overload. Also, assuming type x is not really int in your code, are you sure that there is an equality operator that can work with a constant member of that type?

+4
source

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 a method definition (what you indicated above) const, do you also remember to change the method declaration?

+2
source

Works great 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; } 
0
source

Publish a complete program that does not 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 does not call a function that you think is [Edit: more likely stupid of me, myList is not std::list ]. Reducing to a small program that demonstrates the problem is likely to reveal the cause, because at some point you will remove something and it will start working.

0
source

Source: https://habr.com/ru/post/1304529/


All Articles