Reading code using C ++ 11 lambdas

I REALLY love lambdas and have the ability to use them in C ++ - it's a pleasure. But since I'm used to Haskell, where lambdas fits very well into the syntax, I try my best to use them in C ++ without writing unreadable cluttered long lines of code.

So, as an example, suppose I would write this:

vector<double> foo(10,0.2); for_each(foo.begin(), foo.end(), [](double x){ std::cout << x << " ";}) 

It's not that hard to read, the lambda expression is pretty small. But if I have a function with two or three lines inside this for_each, this could be 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 begins to annoy for a long time and is difficult to read to my taste ...

What are 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 that? I still think this syntax seems a bit unnatural and hard to read ... :(

+7
source share
6 answers

I usually go for

 for_each(foo.begin(), foo.end(), [](double x) { std::cout << "hello!" x += bar()/(1+bar()); std::cout << x << " "; }); 

I wrote a few hundred lines of lambdas.

+9
source

If you prefer, you can call your lambda separately auto :

 auto const baz = [](double x) { std::cout << "hello!" x += bar()/(1+bar()); std::cout << x << " "; }; std::for_each(foo.begin(), foo.end(), baz); 
+6
source

Hm ...

 for_each(foo.begin(), foo.end(), [] (double x) { std::cout << "hello!" x += bar()/(1+bar()); std::cout << x << " "; }); for (auto x : foo) { std::cout << "hello!"; x += bar()/(1+bar()); std::cout << x << " "; } 
+3
source

I like to look at lambda as just another function declaration, and thus follow the same conventions that I use for other functions, within reason:

 // when lambdas are present, I break the enveloping method params for_each( foo.begin(), foo.end(), [] (double x) // I also like to split the brackets, just like with any function { std::cout << "hello!" x += bar()/(1+bar()); std::cout << x << " "; }); // the closing parenthesis is left with the closing bracket 
+2
source

I would say if the code for lambda is more than one or, possibly, two operators, this should be a separate named function.

+1
source

Publish mine

 std::vector<int> a; std::find_if(a.begin() , a.end() , [&](int i) { return i == 0; }); 
+1
source

All Articles