C++ USES the find_if function instance of STL in member functions
- 2020-04-02 02:49:24
- OfStack
This article illustrates how C++ USES the find_if function of STL in member functions. Share with you for your reference. Specific methods are analyzed as follows:
In general, STL's find_if function is powerful enough to perform a lookup using the input function substitution equal operator (there is a lot of information on the web, but I won't go into it here).
Such as finding an array of odd number, you can use the following code completion (specific reference 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(10);
myvector.push_back(25);
myvector.push_back(40);
myvector.push_back(55);
it = find_if (myvector.begin(), myvector.end(), IsOdd);
cout << "The first odd value is " << *it << endl;
return 0;
}
Operation results:
The first odd value is 25
What happens if you add this code to a class and write it as a member of the class?
For example, the following class 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(10);
myvector.push_back(25);
myvector.push_back(40);
myvector.push_back(55);
it = find_if (myvector.begin(), myvector.end(), IsOdd);
cout << "The first odd value is " << *it << endl;
return 0;
}
};
int main()
{
CTest t1;
t1.test();
return 0;
}
Errors like the following occur:
Error C3867: 'CTest::IsOdd': function call missing argument list; Use '&CTest::IsOdd' to create a pointer to member
Today I encountered this problem, here is the solution posted for reference only:
It = find_if (myvector. Begin (), myvector. End (), IsOdd);
To:
It = find_if (myvector. The begin (), myvector. The end (), STD: : bind1st (STD: : mem_fun (& CTest: : IsOdd), this));
Bind1st function and mem_fun function plus this pointer.
Complete sample code click here (link: http://xiazai.jb51.net/201410/yuanma/stl_find_if_inMemeberFun (jb51.net). Rar).
Hope that the article described in the C++ programming to help you.