Advantages of std::for_each over for loop

2019-01-08 03:28发布

Are there any advantages of std::for_each over for loop? To me, std::for_each only seems to hinder the readability of code. Why do then some coding standards recommend its use?

20条回答
疯言疯语
2楼-- · 2019-01-08 03:52

I used to dislike std::for_each and thought that without lambda, it was done utterly wrong. However I did change my mind some time ago, and now I actually love it. And I think it even improves readability, and makes it easier to test your code in a TDD way.

The std::for_each algorithm can be read as do something with all elements in range, which can improve readability. Say the action that you want to perform is 20 lines long, and the function where the action is performed is also about 20 lines long. That would make a function 40 lines long with a conventional for loop, and only about 20 with std::for_each, thus likely easier to comprehend.

Functors for std::for_each are more likely to be more generic, and thus reusable, e.g:

struct DeleteElement
{
    template <typename T>
    void operator()(const T *ptr)
    {
        delete ptr;
    }
};

And in the code you'd only have a one-liner like std::for_each(v.begin(), v.end(), DeleteElement()) which is slightly better IMO than an explicit loop.

All of those functors are normally easier to get under unit tests than an explicit for loop in the middle of a long function, and that alone is already a big win for me.

std::for_each is also generally more reliable, as you're less likely to make a mistake with range.

And lastly, compiler might produce slightly better code for std::for_each than for certain types of hand-crafted for loop, as it (for_each) always looks the same for compiler, and compiler writers can put all of their knowledge, to make it as good as they can.

Same applies to other std algorithms like find_if, transform etc.

查看更多
太酷不给撩
3楼-- · 2019-01-08 03:53

I find for_each to be bad for readability. The concept is a good one but c++ makes it very hard to write readable, at least for me. c++0x lamda expressions will help. I really like the idea of lamdas. However on first glance I think the syntax is very ugly and I'm not 100% sure I'll ever get used to it. Maybe in 5 years I'll have got used to it and not give it a second thought, but maybe not. Time will tell :)

I prefer to use

vector<thing>::iterator istart = container.begin();
vector<thing>::iterator iend = container.end();
for(vector<thing>::iterator i = istart; i != iend; ++i) {
  // Do stuff
}

I find an explicit for loop clearer to read and explicity using named variables for the start and end iterators reduces the clutter in the for loop.

Of course cases vary, this is just what I usually find best.

查看更多
The star\"
4楼-- · 2019-01-08 03:54

For loop can break; I dont want to be a parrot for Herb Sutter so here is the link to his presentation: http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-835T Be sure to read the comments also :)

查看更多
贪生不怕死
5楼-- · 2019-01-08 03:56

You can have the iterator be a call to a function that is performed on each iteration through the loop.

See here: http://www.cplusplus.com/reference/algorithm/for_each/

查看更多
男人必须洒脱
6楼-- · 2019-01-08 03:57

If you frequently use other algorithms from the STL, there are several advantages to for_each:

  1. It will often be simpler and less error prone than a for loop, partly because you'll be used to functions with this interface, and partly because it actually is a little more concise in many cases.
  2. Although a range-based for loop can be even simpler, it is less flexible (as noted by Adrian McCarthy, it iterates over a whole container).
  3. Unlike a traditional for loop, for_each forces you to write code that will work for any input iterator. Being restricted in this way can actually be a good thing because:

    1. You might actually need to adapt the code to work for a different container later.
    2. At the beginning, it might teach you something and/or change your habits for the better.
    3. Even if you would always write for loops which are perfectly equivalent, other people that modify the same code might not do this without being prompted to use for_each.
  4. Using for_each sometimes makes it more obvious that you can use a more specific STL function to do the same thing. (As in Jerry Coffin's example; it's not necessarily the case that for_each is the best option, but a for loop is not the only alternative.)

查看更多
我只想做你的唯一
7楼-- · 2019-01-08 03:58

for is for loop that can iterate each element or every third etc. for_each is for iterating only each element. It is clear from its name. So it is more clear what you are intending to do in your code.

查看更多
登录 后发表回答