c++ - 使用累加对包含 long long int 的 vector 求和

标签 c++ accumulate

#include <iostream>
#include <vector>
#include <numeric>
#include <iterator>

using namespace std;

int main()
{
    int N;
    cin>>N;
    long long int x,sum=0;
    std::vector<long long int> v;
    for(int i=0;i<N;i++)
    {
        cin>>x;
        v.push_back(x);
    }
    /*vector<long long int>::iterator itr;
    itr = v.begin();
    for(itr=v.begin();itr<v.end();itr++)
        sum += *itr;*/
    sum = accumulate(v.begin(),v.end(),0);
    cout<<sum;
    return 0;
}

我的程序使用 accumulate 返回抽象值,但如果我使用 for 循环,答案就来了。

最佳答案

std::accumulate 有一个小陷阱,即您传递的初始值。人们很容易忽略这个值用于推导参数 T 也是返回类型(并且返回类型不是 necesarily the value_type 容器)。通过传递一个 long long 作为初始值来修复它:

    sum = accumulate(v.begin(),v.end(),0LL);

关于c++ - 使用累加对包含 long long int 的 vector 求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46691506/

相关文章:

c++ - 接收Cpp : how to control subject observer's lifetime when used with buffer_with_time

c++编译错误涉及方法重载的2个模板函数

c++ - 为什么我需要在以下示例中的 block_cache.h 之前包含 block_cache_key.h 和 block.h?

c++ - 将函数引用传递给该函数内部的结构

python - Qt:尝试在 qt 中使用 python.h 时 undefined symbol

c++ - 构造函数参数和同名成员

python - 如何折叠/累积一个 numpy 矩阵乘积(点)?

c++ - accumulate 的 Functor 有什么要求?

SQL Server 2008 - 累积列

c++ - 是否可以将 std::accumulate 与 std::min 一起使用?