Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for_each and transform

for_each(ivec.begin(),ivec.end(),
        []( int& a)->void{ a = a < 0 ? -a : a; 
    });

transform(ivec.begin(),ivec.end(),ivec.begin(),
        [](int a){return a < 0 ? -a : a;
    });

I am currently learning lambdas and I am curious how the two implementations, that I have posted above, differ?

like image 441
Maik Klein Avatar asked Sep 11 '26 22:09

Maik Klein


2 Answers

The two implementations you show do not differ logically (assuming you get the first version right by adding a return). The first one modifies elements in place while the last one overwrites its elements with new values.

The biggest difference I see, with transform you just can pass abs instead of a lambda that reimplements it.

like image 178
K-ballo Avatar answered Sep 14 '26 11:09

K-ballo


transform is what would, in a functional language, be called map. That is, it applies a function to every element in the input range, and stores the output into an output range. (So it is generally intended to not modify the inputs, and instead store a range of outputs)

for_each simply discards the return value from the applied function (so it might modify the inputs).

That's the main difference. They are similar, but designed for different purposes.

like image 41
jalf Avatar answered Sep 14 '26 12:09

jalf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!