I was solving this.
I encountered a problem while using std::accumulate
.
I noticed that accumulate(v.begin(), v.end(), 0L)
behaves differently in sublimText/Ideone and Codeforces.
for example,
int main() {
vector<long long> v{1,-1000000000,1,-1000000000,1,-1000000000};
long long sum = accumulate(v.begin(), v.end(), 0L);
cout<<sum;
}
in sublimeText or Ideone: prints -2999999997
and in Codeforces prints 1294967299
.
however, when 0L is changed to 0LL in accumulate function, both sublime text and CF returns the right sum (-2999999997)
is this expected? can someone help me understand this weird behavior?
0L= long (32 bits) 0LL= long long(64 bits)
yeah! but the question is why does it work in ideone and not on codeforces?
is there any difference I should be aware of?
Probably long is 64-bit on ideone. In c++ types like int or long have no fixed size and are architecture-defined
First of all, this has nothing to do with Sublime Text. Sublime Text is a text editor, not a compiler.
Yes, this is expected.
0L
is of typelong
,0LL
is of typelong long
. Instd::accumulate
, the return type is the same as the type of the last argument. cppreference even warns of this situation:In 32-bit GCC,
long
is a 32-bit data type whilelong long
is a 64-bit data type. You probably used 64-bit GCC wherelong
andlong long
are both 64 bits. In short, you get this weird value because of an overflow.It's not really about the compiler either. It can differ by platform/os. long is 32 bit on (mainly) windows, long is 64 bit mostly everywhere else. (Assuming not exotic and not ancient hardware.)
https://en.wikipedia.org/wiki/64-bit_computing#64-bit_data_models