ZijingWu ZijingWu - 1 month ago 9x
C++ Question

Why std::transform doesn't guarantee the order (but for_each guarantee the order)? Doesn't this allow trick implementation for performance?

I just realize the standard doesn't guarantee the order of applying function callback in

. And it doesn't allow the callback function or functor have side effect. But at the same time
actually guarantee the order.

One guess is the transform can using high performance algorithm which doesn't guarantee order, But O(N) is the best algorithm already.

So why the standard doesn't make the
have the behavior as
from the view of apply callback function order? The user will benefit form this guarantee.


This non-restrictive definition allows for parallel computing. An implementation may choose to apply transform function using several threads. See also related question: STL algorithms and concurrent programming

Think of it as a semantic difference in algorithms (that is, that represents programmer's intent rather than being just another tool). With for_each you state that you need a sequential scan. With transform you state that you only need to aply a function to every item in the container, but you don't care how it will be done.