If I like to accumulate the absolute values of a std::vector
, I can use a lambda to calculate the absolute value and add it to the sum of std::accumulate
(live demo).
#include <numeric>
#include <vector>
int main (){
std::vector<int> vec {1,2,3,-4};
auto abs_val =[](auto val, auto sum){return sum + std::fabs(val);};
return std::accumulate(vec.begin(), vec.end(), 0, abs_val);
}
I would like to write
return std::accumulate(vec.begin(), vec.end(), 0, std::fabs());
but this does not compile, since a function with the two arguments sum
and value
is expected.
Is there a more elegant way to write this? Do I need the lambda? Can I get rid of it?