Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute the sum of part of the vector using std:: accumulate

Having this vector

vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

how can I compute the sum of the first half of it (which is 15) using the accumulate function?

Can I do this using the for loop with only the iterators (not numerical indexes)?

like image 924
Slazer Avatar asked Oct 26 '12 17:10

Slazer


People also ask

How do you find the sum of a vector value in C++?

Sum up of all elements of a C++ vector can be very easily done by std::accumulate method. It is defined in <numeric> header. It accumulates all the values present specified in the vector to the specified sum.

What does std :: accumulate do?

std::accumulate() is a built-in function in C++'s Standard Template Library. The function takes in a beginning iterator, an ending iterator, initial value, and (by default) computes the sum of the given initial value and the elements in the given range. The function can also​ be used for left folding.

How do you find the sum of a vector?

To add or subtract two vectors, add or subtract the corresponding components. Let →u=⟨u1,u2⟩ and →v=⟨v1,v2⟩ be two vectors. The sum of two or more vectors is called the resultant. The resultant of two vectors can be found using either the parallelogram method or the triangle method .

What is accumulate return C++?

It returns the result of accumulating all the values in the range [first,last) to init.


2 Answers

You can

accumulate(v.begin(), v.begin()+int(v.size()/2), 0)

if v is your vector.

You can also write a loop:

int sum = 0;
for (vector<int>::iterator it = v.begin(); it != v.begin+int(v.size()/2); ++it) {
    sum += *it;
}
like image 103
alestanis Avatar answered Sep 19 '22 20:09

alestanis


To work with just the first half you have to get iterators that cover just that range. Usually people want to work with an entire container and so they use begin and end functions, but that's not the only way:

auto begin = std::begin(v);
auto middle = std::begin(v) + v.size()/2; // works for random access iterators

auto middle = begin;
std::advance(middle, v.size()/2);

advance works for input iterators or better, but for input iterators which are not also one of the other types the items that are advanced passed won't be accessible anymore.

auto middle = std::next(begin, v.size()/2); // C++11. works for forward iterators

And these are only a few of the available operations you can perform on the different types of iterators.


So now that you can create iterators that specify your desired range you can use them either in std::accumulate or a manual for loop:

std::accumulate(std::begin(v), std::next(std::begin(v), v.size()/2), 0);

for (auto begin(std::begin(v)), end(begin+v.size()/2); begin!=end; ++begin) {
    ...
}
like image 40
bames53 Avatar answered Sep 20 '22 20:09

bames53