Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code readability with c++11 lambdas

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... :(

like image 390
Rafael S. Calsaverini Avatar asked May 26 '11 18:05

Rafael S. Calsaverini


People also ask

Do lambda functions make code more readable?

Lambda functions are a brilliant way to make code more readable and concise.

What is the correct syntax for Lambda Expression in C++11?

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; };

Are lambdas faster than functions C++?

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.

When should I use lambdas C++?

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.


1 Answers

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.

like image 139
Puppy Avatar answered Sep 30 '22 14:09

Puppy