Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) std::accumulate

 

Algorithm to accumulate a range. std::accumulate is defined in numeric.h. Use accumulate_if if you need to supply a predicate.

 

With std::accumulate, for example, you could sum up the values of a std::vector like the example below:

 

#include <cassert>
#include <vector>
#include <numeric>
 
int main()
{
  //Create a std::vector
  std::vector<int> v;
  for (int i=0; i!=10; ++i) { v.push_back(i); }
 
  //Sum the std::vector
  const int sum = std::accumulate(v.begin(), v.end(), 0 ); // '0' is the initial value
 
  //Assume std::accumulate works correctly
  assert(sum == 45);
}

 

 

 

 

 

A definition of std::accumulate

 

template <class InputIterator, class T>
T accumulate (InputIterator first, InputIterator last, T init)
{
  while (first != last) init = init + *first++;
  return init;
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict