Summing a vector containing a long long int using accumulation

#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 returns an abstract value using accumulation, but if I use a for loop, the answer will be ready.

+4
source share
1 answer

std::accumulatehas a small trap, which is the initial value that you pass. It can be easily overlooked that this value is used to display a parameter Tthat is also a return type (and the return type is not , namely the value_typecontainer). Correct it by passing long longas the initial value:

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

or for paranoids (sorry, just jokes with raw castes are really not good):

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

Source: https://habr.com/ru/post/1687316/


All Articles