The C++ Standard Library consists of the header, <numeric>
which defines a collection of functions to perform certain operations on sequences of numeric values. accumulate()
is a method in the STL that returns the result of accumulating all the values in the range specified for a given container.
Syntax:
accumulate( iterator_begin, iterator_end, init) //uses operator '+' to sum up the elements accumulate( iterator_begin, iterator_end, init, binary_op) // uses the given binary function op to work with elements
Parameters: The accumulate()
method accepts 4 parameters
- iterator_begin: Iterator to the initial position
- iterator_end: Iterator to the final position ( Note: the range is [iterator_begin,iterator_end) )
- init: Initial value for accumulator
- binary_op: Binary operation function object that will be applied.
Return value: The result of accumulating all elements in the range
Example of accumulate() method
#include <iostream> #include <numeric> #include <vector> using namespace std; int main() { vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); cout<<"Sum of elements: "<< accumulate( v.begin(), v.end(), 0 ) << endl; cout<<"Product of elements: "<< accumulate( v.begin(), v.end(), 1, multiplies<int>() ) << endl; }
Output:
Sum of elements: 10 Product of elements: 24