13
#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.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Rakshit Verma
  • 131
  • 1
  • 4
  • @tobi303 : That sounds like an answer. (In fact, it *is* the answer. The OP has instantiated `std::accumulate::iterator, int>`) – Martin Bonner supports Monica Oct 11 '17 at 15:01
  • `std::accumulate` has a separate template parameter for the initial value. No restriction that it has to be the same type as the elements. The only possibly likely problem with using `int` there is overflow, really. – chris Oct 11 '17 at 15:03
  • @chris: Well yes. But if you have a vector of long long int, it is highly likely that values >2G are at least possible - and hence that overflow *will* be the problem. – Martin Bonner supports Monica Oct 11 '17 at 15:32

1 Answers1

34

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);
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185