1、仿函数
仿函数(functor),即使一个类使用上看上去像函数。其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类。
仿函数的作用:
有时仿函数的使用是为了函数拥有类的性质,以达到安全传递函数指针,依据函数生成对象,甚至是让函数之间有继承关系,对函数进行运算和操作的效果。
例:
struct MyPlus{
int operator()(const int &a , const int &b) const{
return a + b;
}
};
int main()
{
MyPlus a;
cout << MyPlus()(1,2) << endl; //1、通过产生临时对象调用重载运算符
cout << a.operator()(1,2) << endl; //2、通过对象显示调用重载运算符
cout << a(1,2) << endl; //3、通过对象类似函数调用 隐示地调用重载运算符
return 0;
}
2、lambda表达式是对象不是类型
编译器在实现lambda时,将其转化为函数对象(仿函数functor)。仿函数和 Lambda 表达式是可以有状态的,也就是说它们可以含数据成员,而函数指针就无状态可言,比如下面这种情况就无法用函数指针,只能用仿函数或 Lambda 表达式。
例:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void printWithLambda(const vector<int> &vec, int standard)
{
for_each(vec.begin(), vec.end(), [standard] (int elem) {
if (elem > standard)
{
cout << elem << " ";
}
});
}
struct Printor
{
public:
Printor(int standard) :_standard(standard) {}
void operator()(int elem)const {
if (elem > _standard)
{
cout << elem << " ";
}
}
private:
int _standard;
};
void printWithFunctor(const vector<int> &vec, int standard)
{
for_each(vec.begin(), vec.end(), Printor(standard));
}
int main()
{
int arr[] = { 5, 4, 6, 8, 1 };
int size = sizeof arr / sizeof *arr;
vector<int> vec(arr, arr + size);
cout << "输出最小的数:" << endl;
int standard;
cin >> standard;
printWithFunctor(vec, standard);
cout << endl;
printWithLambda(vec, standard);
cout << endl;
system("pause");
return 0;
}
输出: