向量 (STL) 中的累加函数给出负和

yas*_*ash 0 c++ stl vector accumulate

当我编写下面的代码时,我得到一个负数 (-294967296)。

#include<iostream>
#include<vector>
#include<numeric>
using namespace std;
int main() {
    vector<long long int> v={1000000000 , 1000000000 , 1000000000 , 1000000000};
    cout<<"Sum of all the elements are:"<<endl;
    cout<<accumulate(v.begin(),v.end(),0);
}
Run Code Online (Sandbox Code Playgroud)

但是当我编写下面的代码时,我得到了一个正数 (2000000000)

#include<iostream>
#include<vector>
#include<numeric>
using namespace std;
int main() {
    vector<long long int> v={1000000000 , 1000000000};
    cout<<"Sum of all the elements are:"<<endl;
    cout<<accumulate(v.begin(),v.end(),0);
}
Run Code Online (Sandbox Code Playgroud)

可能是什么原因?

mch*_*mch 5

std::accumulatehttps : //en.cppreference.com/w/cpp/algorithm/accumulate使用最后一个参数的类型进行计算。

您应该使用accumulate(v.begin(),v.end(),0ll);ll使 成为0一个long long,然后所有计算都完成long long,因此它不会溢出int

示例:https : //ideone.com/QQCYIW

  • 我会推荐“L”,这样它看起来就不像“1” (3认同)