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;
}
I would like to keep the std::transform but without the lambda.
In this case, an equivalent functor is:
Then:
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.