functor就是一个重载了 operator()的类,用这个类生成的实例就像一个函数。(functor就是一个作为函数用的类),在c++11后可以用lambda函数实现同样的功能。
参考链接:stackoverflow
// this is a functor
struct add_x {
add_x(int x) : x(x) {}
int operator()(int y) const { return x + y; }
private:
int x;
};
// 这也是一个functor
struct inc{
int operator()(int _i) { return _i + 1;}
};
// Now you can use it like this:
add_x add42(42); // create an instance of the functor class
int i = add42(8); // and "call" it
assert(i == 50); // and it added 42 to its argument, 检查i是否等于50
std::vector<int> in; // assume this contains a bunch of values)
std::vector<int> out(in.size());
// Pass a functor to std::transform, which calls the functor on every element
// in the input sequence, and stores the result to the output sequence
// add_x(1), 相当于创建了 add_x add1(1)
// add1 相当于一个函数,传入一个int参数, 这个int 会加上 1
std::transform(in.begin(), in.end(), out.begin(), add_x(1));
//相当于
inc i_1;
std::transform(in.begin(), in.end(), out.begin(), i_1);
// 效果和下面这句相同
std::transform(in.begin(), in.end(), out.begin(), [](int x){ return x + 1;});
assert(out[i] == in[i] + 1); // for all i