accumulate() in C++ STL

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.


 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;

    cout<<"Sum of elements: "<< accumulate( v.begin(), v.end(), 0 ) << endl;
    cout<<"Product of elements: "<< accumulate( v.begin(), v.end(), 1, multiplies<int>() ) << endl;


Sum of elements: 10
Product of elements: 24

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]