Can std::transform be replaced by std::accumulate?
Those two algorithms have completely different purpose.
std::accumulate
is known as fold in functional programming world, and it's purpose is iterate over elements of a sequence and apply two-argument folding operation to those elements, with one argument being result of previous fold and other being element of the sequence. It naturally returns the a single result - a fold of all elements of a sequence into one value.
On the other hand, std::transform
copies values from one sequence to another, applying a unary operation to each element. It returns an iterator to the end of sequence.
The fact that you can supply any code as the fold operation allows us to use std::accumulate
as a generic loop replacement, including an option to copy values into some other container, but that it is ill-advised, as the whole reason for introducing those (rather simple) algorithms was to make programs more explicit. Making one algo to perform the task which is normally associated to another algo is less explicit and counter-intuitive.
A generic loop replacement algo is std::for_each, but with range for loops it became largely obsolete and I have not seen it in use for a long time.
Can we always replace
std::transform
withstd::accumulate
?
No. Per cppreference std::accumulate
's binary predicate op
has
op
must not invalidate any iterators, including the end iterators, nor modify any elements of the range involved, and also*last
.
So it can't actually transform the range you give it which is a main use case for std::transform
.