summation of vector containing long long int using accumulation

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-18 22:09:53

问题


#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;
}

My program is returning abstract value using accumulate, but if I use the for loop, the answer is coming.


回答1:


std::accumulate has a small pitfall that is the initial value that you pass. One can easily overlook that this value is used to deduce the parameter T that is also the return type (and the return type is not necesarily the value_type of the container). Fix it by passing a long long as initial value:

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


来源:https://stackoverflow.com/questions/46691506/summation-of-vector-containing-long-long-int-using-accumulation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!