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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With