Welshie321
Welshie321

Reputation: 35

Get the sum of a vector

How do I return the sum of this vector array of integers? The code I have below returns the wrong value.

int simpleArraySum(vector<int> ar) {
    int sum = 0;
    int length = sizeof(ar);
    for (int i = 0; i < length; i++){
        sum += ar[i];
    }
    return sum;

}

Upvotes: 1

Views: 503

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

For starters the vector should be passed to the function by reference. Otherwise a redundant copy of the vector will be created. Moreover the parameter should be declared with constant reference because the vector itself is not changed in the function.

For the sum you should use the type long long int because it is not excluded that there can be an overflow.

This declaration

int length = sizeof(ar);

does not make sense. The variable length keeps the size of the object of the type std::vector<int> not the number of elements stored in the vector.

So the function can be defined for example the following way

long long int simpleArraySum( const std::vector<int> & ar )
{
    long long int sum = 0;

    for ( const auto &item : ar ) sum += item;

    return sum;
}

Another approach is to use the standard algorithm std::accumulate declared in the header <numeric>. For example

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

//...

long long int simpleArraySum( const std::vector<int> & ar )
{
    return std::accumulate( std::begin( ar ), std::end( ar ), 0ll );
}

Upvotes: 3

Acorn
Acorn

Reputation: 26196

Use std::accumulate:

int simpleArraySum(vector<int> ar) {
    return std::accumulate(ar.begin(), ar.end(), 0);
}

In any case, your length initialization is wrong, it should be:

int length = ar.size();

If you are still having unexpected results, it is likely that you are either under/overflowing sum (likely, use a wider type) or that you have too many elements to fit in an int (unlikely, switch to std::size_t or use a range-for loop instead).

Upvotes: 1

Related Questions