C++ Numeric Library - accumulate



Description

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

Declaration

Following is the declaration for std::accumulate.

C++98

	
template <class InputIterator, class T>
   T accumulate (InputIterator first, InputIterator last, T init);
template <class InputIterator, class T, class BinaryOperation>
   T accumulate (InputIterator first, InputIterator last, T init,
                 BinaryOperation binary_op);

C++11

template <class InputIterator, class T>
   T accumulate (InputIterator first, InputIterator last, T init);
template <class InputIterator, class T, class BinaryOperation>
   T accumulate (InputIterator first, InputIterator last, T init,
                 BinaryOperation binary_op);
  • first, last − It iterators to the initial and final positions in a sequence.

  • init − It is an initial value for the accumulator.

  • binary_op − It is binary operation.

Return Value

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

Exceptions

It throws if any of binary_op, the assignments or an operation on an iterator throws.

Data races

The locale object is modified.

Example

In below example for std::accumulate.

#include <iostream>    
#include <functional>   
#include <numeric>     

int myfunction (int x, int y) {return x+2*y;}
struct myclass {
   int operator()(int x, int y) {return x+3*y;}
} myobject;

int main () {
int init = 100;
   int numbers[] = {5,10,20};

   std::cout << "using default accumulate: ";
   std::cout << std::accumulate(numbers,numbers+3,init);
   std::cout << '\n';

   std::cout << "using functional's minus: ";
   std::cout << std::accumulate (numbers, numbers+3, init, std::minus<int>());
   std::cout << '\n';

   std::cout << "using custom function: ";
   std::cout << std::accumulate (numbers, numbers+3, init, myfunction);
   std::cout << '\n';

   std::cout << "using custom object: ";
   std::cout << std::accumulate (numbers, numbers+3, init, myobject);
   std::cout << '\n';

   return 0;
}

The output should be like this −

using default accumulate: 135
using functional's minus: 65
using custom function: 170
using custom object: 205
numeric.htm
Advertisements