Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 556
XYZCODE123 Avatar asked Sep 23 '19 19:09

XYZCODE123


2 Answers

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.

like image 74
SergeyA Avatar answered Nov 07 '22 02:11

SergeyA


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.

like image 29
NathanOliver Avatar answered Nov 07 '22 01:11

NathanOliver