I have a function that generates some large numbers, puts them in a vector, sums them, an returns the sum. I have been using std::accumulate
to calculate the sum, however, after some testing, I realized it was not returning the expected sum.
typedef unsigned long long ull;
ull sum(ull kLimit)
{
ull testSum = 0;
vector<ull> numbers;
for (ull n = 0; n < kLimit; ++n) {
if (/* number I want */) {
numbers.push_back(n);
// directly sum for testing
testSum += n;
}
}
ull sum = accumulate(begin(numbers), end(numbers), 0);
return sum;
}
I would expect the value of sum
and testSum
to be equal. However, sum is equal to 470064632
and test sum is equal to 82074443256
, which is the expected value.
I tried reducing the limit to a much smaller number (500), and the values of sum
and testSum
were equal. This makes me think the error is overflow with accumulate
, I'm not sure what the problem could be though. I am compiling with VS2012 for a x64 platform.
It does look like an overflow error: the numbers are 0x131C049DF8 and 0x1C049DF8.
Try casting your final parameter 0
to type ull
, because the type returned by accumulate is the type of that final parameter:
T accumulate(InputIt first, InputIt last, T value) { ... }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.