Reputation: 4771
I am trying to understand how the find_if function works, and I am following the example in this reference:
http://www.cplusplus.com/reference/algorithm/find_if/
When I follow the example given in the above reference, meaning when I use main(), everything works fine. But when I try to include that example inside a class (as I have shown below) I get this error when I compile:
error: argument of type ‘bool (A::)(int)’ does not match ‘bool (A::*)(int)’
Inside my class:
bool A::IsOdd (int i) {
return ((i%2)==1);
}
void A::function(){
std::vector<int> myvector;
myvector.push_back(10);
myvector.push_back(25);
myvector.push_back(40);
myvector.push_back(55);
std::vector<int>::iterator it = std::find_if (myvector.begin(), myvector.end(), IsOdd);
std::cout << "The first odd value is " << *it << '\n';
}
Can anyone help me understand why this is happening?
Upvotes: 1
Views: 772
Reputation: 105886
A::isOdd
needs to be a static
method. Otherwise it can only be used in conjunction with a specific A
. Since isOdd
doesn't depend on member fields at all it is save to change it into a static
method. Even more, since it doesn't depend on the class at all, you can just create a global isOdd
:
bool isOdd(int i){
return i % 2;
}
EDIT: As suggested by chris, you can also use a simple lambda (C++11):
auto it = std::find_if (
myvector.begin(),
myvector.end(),
[](int i) -> bool{ return i % 2; }
);
Upvotes: 5