I REALLY love lambdas and having the ability to use them in C++ is a pleasure. But, as I'm used to Haskell, where lambdas fit really well into the syntax, I'm struggling with how to use them in C++ without writing unreadable cluttered long code lines.
So, as an example, suppose I'd write this:
vector<double> foo(10,0.2);
for_each(foo.begin(), foo.end(), [](double x){ std::cout << x << " ";})
this is not so difficult to read, the lambda expression is pretty small. But if I have a two or three line long function inside that for_each, this could become a problem for my code-reading-skills:
vector<double> foo(10,0.2);
randomNumberGenerator bar;
for_each(foo.begin(), foo.end(), [](double x){ std::cout << "hello!"; x+=bar()/(1+bar()); std::cout << x << " ";})
//sorry, I couldn't think of a less stupid example...
This line is starting to get annoyingly long and difficult to read for my taste...
What is your preferred code conventions for this case? Should I write:
for_each(foo.begin(), foo.end(),
[] (double x) {
std::cout << "hello!"
x += bar()/(1+bar());
std::cout << x << " ";
});
or something like it? I still think this syntax feels a bit unnatural and difficult to read... :(
Lambda functions are a brilliant way to make code more readable and concise.
Lambdas can both capture variables and accept input parameters. A parameter list (lambda declarator in the Standard syntax) is optional and in most aspects resembles the parameter list for a function. auto y = [] (int first, int second) { return first + second; };
sorting - Why is a C++ Lambda function much faster as compare function than an equivalent object - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.
We have seen that lambda is just a convenient way to write a functor, therefore we should always think about it as a functor when coding in C++. We should use lambdas where we can improve the readability of and simplify our code such as when writing callback functions.
I usually go for
for_each(foo.begin(), foo.end(), [](double x) {
std::cout << "hello!"
x += bar()/(1+bar());
std::cout << x << " ";
});
I've written some several hundred line lambdas.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With