This article illustrates the method for C + + to use STL find_if function in member functions. Share to everyone for your reference. The specific methods are analyzed as follows:
In general, the STL find_if function is very powerful, you can use the input function instead of the operator to perform the lookup function (this online has a lot of information, I will not say more here).
Looking for an odd number in an array, for example, can be done with the following code (refer here: http://www.cplusplus.com/reference/algorithm/find_if/):
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
BOOL IsOdd (int i) {return
((i%2) ==1);
}
int main () {
vector<int> myvector;
Vector<int>::iterator it;
Myvector.push_back (ten);
Myvector.push_back (a);
Myvector.push_back ();
Myvector.push_back ();
it = find_if (Myvector.begin (), Myvector.end (), isodd);
cout << "The odd value is" << *it << Endl;
return 0;
}
Run Result:
If you add the above code to the class, write the member function of the class, what is the effect?
such as the following code:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
Class CTest
{public
:
bool isodd (int i) {return
((i%2) ==1);
}
int Test () {
vector<int> myvector;
Vector<int>::iterator it;
Myvector.push_back (ten);
Myvector.push_back (a);
Myvector.push_back ();
Myvector.push_back ();
it = find_if (Myvector.begin (), Myvector.end (), isodd);
cout << "The odd value is" << *it << Endl;
return 0;
}
;
int main ()
{
ctest t1;
T1.test ();
return 0;
}
An error similar to the following appears:
Error C3867: ' ctest::isodd ': function call missing argument list; Use ' &ctest::isodd ' to create a pointer
Today I encountered this problem, the solution is posted here for reference only:
it = find_if (Myvector.begin (), Myvector.end (), isodd);
To
it = find_if (Myvector.begin (), Myvector.end (), std::bind1st (Std::mem_fun (&ctest::isodd), this);
With the bind1st function and the Mem_fun function plus this pointer.
Full instance code click here to download the site.
I hope this article will help you with the C + + program design.