Home > database >  Are there any differences between accumulate(a.begin(), a.end(), 0) or accumulate(a.begin(), a.end()
Are there any differences between accumulate(a.begin(), a.end(), 0) or accumulate(a.begin(), a.end()

Time:11-05

When I write long long sum = accumulate(a.begin(), a.end(), 0); or long long sum = accumulate(a.begin(), a.end(), 0ll); both give me the same result then why use 0ll instead of only 0 (where a is std:: vector<int> a(n))?

My full code is here

CodePudding user response:

std::accumulate is a template, when being passed 0 (which is supposed to be the initial value of the sum), the 2nd template parameter will be deduced as int, then the sum is performed on int, the return type is int too. Then in long long sum = accumulate(a.begin(), a.end(), 0);, the returned int is converted to long long and assigned to sum.

On the other hand, accumulate(a.begin(), a.end(), 0ll); performs sum on long long and returns a long long.

If the sum won't cause overflow on int, you'll get the same result on both cases. Otherwise, the 2nd one should be perferred.

CodePudding user response:

Functionally there's no difference at all but using Oll instead O will perform summation in long long and also will return result in long long, which will prevent integer overflow in case of large integer sums which exceed normal int range.

  • Related