简体   繁体   中英

Can std::transform be replaced by std::accumulate?

I have a general question. Can we always replace std::transform with std::accumulate ? I have seen this replacement in many cases/examples. So is this possible in theory, and if it is then why std::transform was introduced?

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 with std::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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM