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)?
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.
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.
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 .
It returns the result of accumulating all the values in the range [first,last) to init.
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;
}
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) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With