Today, I want to share something that was blowing my mind when I tried to implement this simple operation:
I found different ways to perform the same operat
If I am accumulating elements of an array, I am expecting to get the same type as a result.
Your expectation is wrong (though it is not quite clear what "same type as result" means), as you can clearly see from std::accumulate documentation:
template< class InputIt, class T >
T accumulate( InputIt first, InputIt last, T init );
template< class InputIt, class T, class BinaryOperation >
T accumulate( InputIt first, InputIt last, T init,
BinaryOperation op );
return type is exactly the same type you use for initial value. The same effect you can have on the loop:
auto result = 0; // vs auto result = 0.0;
for (auto i = 0; i < input.size(); ++i) {
result += input[i] * input[i];
}
Why did the standard decide to perform it in this way?
Because this way you can decide what type you use to aggregate. Note std::accumulate
can be used for left fold and cases when T
not equal to std::iterator_traits
not less often (probably even more) than when they match.