函数对象常用在stl的算法中,用于特殊的匹配定制功能。
在执行的函数对象中构造函数和重载()函数的关系先后顺序
如下代码:
find_if(v.begin(), v.end(), search_num(4))
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
template <typename T>
class search_num
{
T m_val;
public:
search_num(T value):m_val(value) { cout << " construct " <<value<< endl; }
bool operator()(const T val){
cout << "opeatorr()" << endl;
return (m_val == val);
}
};
int main()
{
vector<int> v;
for (int i = 1; i < 6; i++)
{
v.push_back(i);
}
vector<int>::iterator it = find_if(v.begin(), v.end(), search_num<int>(4));
if (it != v.end())
{
cout << " find num " << *it << endl;
}
else
{
cout << "not find the num" << endl;
}
return 0;
}
运行结果:
construct 4
opeatorr()
opeatorr()
opeatorr()
opeatorr()
find num 4
结论:
先执行构造函数,在执行重载函数