Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

summation of vector containing long long int using accumulation

Tags:

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

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

like image 730
Rakshit Verma Avatar asked Oct 11 '17 14:10

Rakshit Verma


People also ask

How do you use long long in vector?

vector <long long> v(n,0) means you're creating a vector of size n and initializing its elements to 0. vector < vector <long long> > (n+1, vector <long long>(r+1,0)) means you're creating a vector of vectors of size n and initializing the elements with vectors of size r+1 and those vectors are initialized to 0.

What is the use of accumulate function in C++?

1) accumulate(): This function returns the sum of all the values lying in a range between [first, last) with the variable sum.

How do you use accumulate?

He aimed to accumulate a million dollars before he turned thirty. Lead can accumulate in the body until toxic levels are reached. These toxins accumulate in the lungs.


1 Answers

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);
like image 63
463035818_is_not_a_number Avatar answered Sep 22 '22 11:09

463035818_is_not_a_number