In §25.2.4.2 of the C++ standard (std::for_each
):
template<class InputIterator, class Function> Function
for_each(InputIterator first, InputIterator last, Function f);
Effects: Applies f to the result of dereferencing every iterator in the range [first,last), starting from first and proceeding to last - 1.
f
is applied to the elements of a container in order?I originally said no, but I think it does mean that, yes. Other algorithms don't include that specific wording.
Maybe, the parallel mode is an extension, and somewhat experimental, not really claiming to be a 100% conforming implementation of the standard library. (If it does claim that somewhere in the docs I'll fix the docs! ;-)
Range-based for
does not depend on the standard library to work. If std::begin
and std::end
are visible they might be used, but are not required. Also, it would involve packaging up the loop body as a lambda so you have a function object to pass to std::for_each
, which would complicate the specification of range-based for
, which is supposed to have the same semantics and be exactly as efficient as a hand-written for
loop. But the real reason might be that noone thought to do it that way!
If not, why is the range-based for loop in §6.5.4 not implemented as a call to std::for_each? (this would allow range-based for loops to also be automatically parallelized)
Well, std::for_each
is not allowed by the standard to be "automatically parallelized" (it must proceed sequentially, as stated in the standard), so there's that. But more importantly, range-based for
allows other things besides std::for_each
. As a language feature, you get to, for example, break
out of the loop. You can use goto
or other language constructs. And so forth.
std::for_each
is based around calling a function for each iteration. And you can't really "break" out of a function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With