Karthick Subramanian
Karthick Subramanian

Reputation: 53

How to calculate sum of a vector till a specific index using accumulate() in c++

I would like to know if there is anyway to perform Sum of a vector till specific index using accumulate(). Example

vector<int> v ={1,2,3,4,5,6};
int sum = accumulate(v.begin(), till_index_4, 0);

All examples i found says accumulate(v.begin(), v.end(), 0); I tried with iterator also but my code is not compiled. Please let me if there is any possible solutions available.

Upvotes: 3

Views: 3315

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

C++ standard library provides function std::next which takes an iterator into a sequence, and yields another iterator n steps apart. For std::vector iterators this is an O(1) operation.

If you know that n-th position in your vector is valid, you can accumulate as follows:

int sum = accumulate(v.begin(), std::next(v.begin(), 4), 0);

Upvotes: 4

Related Questions