Should I use std::for_each?

前端 未结 9 1352
自闭症患者
自闭症患者 2020-12-08 04:18

I\'m always trying to learn more about the languages I use (different styles, frameworks, patterns, etc). I\'ve noticed that I never use std::for_each so I thought that perh

9条回答
  •  北荒
    北荒 (楼主)
    2020-12-08 04:32

    There is an advantage to using std::for_each instead of an old school for loop (or even the newfangled C++0x range-for loop): you can look at the first word of the statement and you know exactly what the statement does.

    When you see the for_each, you know that the operation in the lambda is performed exactly once for each element in the range (assuming no exceptions are thrown). It isn't possible to break out of the loop early before every element has been processed and it isn't possible to skip elements or evaluate the body of the loop for one element multiple times.

    With the for loop, you have to read the entire body of the loop to know what it does. It may have continue, break, or return statements in it that alter the control flow. It may have statements that modify the iterator or index variable(s). There is no way to know without examining the entire loop.

    Herb Sutter discussed the advantages of using algorithms and lambda expressions in a recent presentation to the Northwest C++ Users Group.

    Note that you can actually use the std::copy algorithm here if you'd prefer:

    std::copy(v.begin(), v.end(), std::ostream_iterator(std::cout, "\n"));
    

提交回复
热议问题