开发者

Code readability with c++11 lambdas

I REALLY 开发者_如何学Pythonlove 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... :(


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 prefer, you can name your lambda separately with auto:

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


Hmm...

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


I like to look at lambdas 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


I'd say if the code for the lambda is more than one or perhaps two statements, it should be a separate named function.


Post mine

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜