C++ functor

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值