是否可以更改此代码,以避免使用C ++ lambda表达式? [英] Is it possible to change this code in order to avoid the use of the C++ lambda expression?

查看:127
本文介绍了是否可以更改此代码,以避免使用C ++ lambda表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码,我想知道如果我可以改变它,以避免使用lambda表达式:

I have this code and I would like to know if I can change it in order to avoid the use of the lambda expression:

#include <vector>
#include <algorithm>
#include <iterator>

class B
{
public:
    B( double b ):b_(b){}
    double b_;
};

class A
{
public:
    double error( const B& b ) const {return a_-b.b_;};
    double a_;
};

int main(int argc, char* argv[])
{
    std::vector< B > bs;
    std::vector< double > ds;

    A a;
    a.a_ = 10;
    bs.push_back( B(1) );
    bs.push_back( B(2) );
    bs.push_back( B(3) );
    std::transform( bs.begin(), bs.end(), 
                    std::back_inserter( ds ), 
                    [&a](const B& b){return a.error(b);} );

    return 0;
}

我想保留 std :: transform

I would like to keep the std::transform but without the lambda.

推荐答案

在这种情况下,等效函子是:

In this case, an equivalent functor is:

struct CallError {
    A &a;
    CallError(A &a) : a(a) {}
    double operator()(const B &b) { return a.error(b); }
};

然后:

std::transform( bs.begin(), bs.end(), 
                std::back_inserter( ds ),
                CallError(a));

请注意,lambda捕获的任何东西都需要函数的相应数据成员。 捕获一切lambda因此有点棘手,因为你需要解决lambda实际使用哪些变量。 lambda为你做的另一件事,在这种情况下,lambda主体由一个单一的return语句组成,它是自动处理返回类型。

Note that anything captured by the lambda needs a corresponding data member of the functor. "Capture everything" lambdas are therefore a little trickier, since you need to work out which variables the lambda actually uses. The other thing that the lambda does for you, in this case where the lambda body consists of a single return statement, is that it automatically works out the return type.

这篇关于是否可以更改此代码,以避免使用C ++ lambda表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆