C++ functor

来源:互联网 发布:商城网络平台建设公司 编辑:程序博客网 时间:2024/05/22 04:40

functor就是一个重载了 operator()的类,用这个类生成的实例就像一个函数。(functor就是一个作为函数用的类),在c++11后可以用lambda函数实现同样的功能。

参考链接:stackoverflow

// this is a functorstruct add_x {  add_x(int x) : x(x) {}  int operator()(int y) const { return x + y; }private:  int x;};// 这也是一个functorstruct 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 classint i = add42(8); // and "call" itassert(i == 50); // and it added 42 to its argument, 检查i是否等于50std::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 会加上 1std::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
原创粉丝点击