Solution to this issue
To fix this issue, you should ensure that the initial value provided to accumulate is of the same data type as the elements in the vector (long long in this case).
Here’s the modified code:
C++
#include <bits/stdc++.h> using namespace std; int main() { long long val = 1e12; vector< long long > v({ val, val, val }); // now take sum of all elements long long sum = accumulate(v.begin(), v.end(), ( long long )0); cout << sum << '\n' ; return 0; } |
3000000000000
Gfact | Why accumulate function in C++ gives wrong answer for large numbers?
The C++ accumulate() function calculates the sum of numerical values under a certain range. It can also be used to effectively iterate and compute the sum of an entire array or a vector with ease.
Syntax of C++ accumulate() function:
accumulate(startRange, endRange, initialValue);
Parameters of C++ accumulate() function:
- startRange: specifies the position in the series from which we want the operation to start
- end-range: specifies the position in the series up to which we want to perform the specific operation
- initialValue: the initial value is given to the accumulate() function, it stores the result of the operation in initialValue.