0

I have tried to use accumulate STL function for long long int data type. But it is showing garbage value in my compiler. But it works for int data type properly.

#include <bits/stdc++.h>
#define ll long long

using namespace std;

int main()
{
    //vector<ll>v={1,2,3,4};
    vector<ll>v={10000000000,2,3,4};
    cout<<accumulate(v.begin(),v.end(),0);

    return 0;
}

It shows right output for the commented line. Is there any problem with long long int?

Nakib
  • 19
  • 4

1 Answers1

1

Accumulator's type is deduced by the sum type. When you put 0 it is taken as 32bit and you got an overflow. To prevent this you need to give 0ll.

#include <iostream>
#include <vector>
#include <numeric>
#include <stdint.h>

using ll = long long int;



int main()
{
    using namespace std;

    vector<ll>v={10000000000 ,2,3,4};
    cout<<accumulate(v.begin(),v.end(),0ll);

    return 0;
}

Also you should not use #include <bits/stdc++.h>. check stackoverflow for more explanation about it.

Also using is better than typedef or #define for defining types.

balu
  • 1,023
  • 12
  • 18
  • 1
    The documentation at [cppreference.com](https://en.cppreference.com/w/cpp/algorithm/accumulate#Common_mistakes) not only agrees with you, but also highlights (something close to) this as a "common mistake". ;) – JaMiT Mar 24 '22 at 05:13
  • Is this true only for accumulate or for other functions also? @JaMiT – Nakib Mar 24 '22 at 05:22
  • @Nakib for many reducing functions the default value is int32. also accept the answer if it helps . – balu Mar 24 '22 at 05:33
  • @Nakib ? I'm not sure how my comment could be applied to other functions, but I went ahead and searched cppreference.com for "common mistake". Based on that search, the page for `std::accumulate` is the only one with a "Common mistake" section, so in that respect my comment is true only for `accumulate`. – JaMiT Mar 24 '22 at 12:38
  • 1
    More generally, the type of `0` is `int`; it may or may not be 32 bits. – Pete Becker Mar 24 '22 at 13:51