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?
This first version:
works by calling the lambda function
once for every element in the range, passing in the elements in the range as arguments. Accordingly, it updates the elements in-place by directly changing their values.
This second version:
works by applying the lambda function
to each of the elements in the range
ivec.begin()toivec.end(), generating a series of values, and then writing those values back to the range starting ativec.begin(). This means that it overwrites the original contents of the range with the range of values produced by applying the function to each array element, so the elements are overwritten rather than modified in-place. The net effect is the same as the originalfor_each, though.Hope this helps!