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.
Range-based
foris 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_ifsubstituted forstd::for_eachallows this as well.)std::for_each, ironically, is the alternative which is actually range based and allows you to select particularbeginandendvalues instead of the whole container. (EDIT: This can be hacked around using a simplerangeclass providingbeginandendmembers, such as provided by Boost.)Also
for_eachmay be more elegant when otherwise using higher-order functions: it can be used as an argument tobind, 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.