仿函数
重载函数调用操作符的类,其对象常称为函数对象(function object),它们是行为类似函数的对象,也叫仿函数(functor),其实就是重载“()”操作符,使得类对象可以像函数那样调用。
1.(仿函数)是一个类,不是一个函数。
2.(仿函数)重载了”() ”操作符使得它可以像函数一样调用。
3. 假定某个类有一个重载的operator(),而且重载的operator()要求获取一个参数,我们就将这个类称为“一元仿函数”(unary functor) ;相反,如果重载的operator()要求获取两个参数,就将这个类称为 “二元仿函数”(binary functor)。
class MP {
public:
void operator()(int v) {
cout << v << endl;
}
};
int main()
{
MP()(1); //匿名对象调用
}
谓词
谓词是指普通函数或重载的operator()返回值是bool类型的函数对象(仿函数)。 如果operator接受一个参数,那么叫做一元谓词,如果接受两个参数,那么叫做二元谓词,谓词可作为一个判断式。
class GreaterThenFive
{
public:
bool operator()(int num)
{
return num > 5;
}
};
//一元谓词
void test01()
{
vector<int> v = { 1,2,3,4,5,6,7,8 };
auto it = find_if(v.begin(), v.end(), GreaterThenFive());
if (it == v.end())
{
cout << "没有找到" << endl;
}
else
{
cout << "找到了: " << *it << endl;
}
}
int main()
{
test01();
}