Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

c++ - Preferred standard use: range based for or std::for_each

In C++11, there are two loops over all elements (range based for and for_each). Is there any reason to prefer one over the other or are there situations where one is a better fit?

for (auto& elem: container) {
  // do something with elem
}

std::for_each(container.begin(), container.end(),
              [](Elem& elem) {
                // do something with elem
              });

My idea would be that the first is simpler and is similar to range based loops in other languages while the second also works for sequences that are not complete containers and the second is more similar to other std-algorithms.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. Range-based for is obviously simpler to read and write. It is specialized for this task.

    EDIT: You can break form a range-for without abusing an exception. (Although std::find_if substituted for std::for_each allows this as well.)

  2. std::for_each, ironically, is the alternative which is actually range based and allows you to select particular begin and end values instead of the whole container. (EDIT: This can be hacked around using a simple range class providing begin and end members, such as provided by Boost.)

    Also for_each may be more elegant when otherwise using higher-order functions: it can be used as an argument to bind, and the third argument is already a functor.

Mainly it's a matter of style. Most readers probably prefer to see for ( auto &a : b ) though, and most implementations now support it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...