Library: Numerics
Function
A generalized numeric operation that accumulates all elements within a range into a single value
#include <numeric>
namespace std {
template <class InputIterator, class T>
T accumulate(InputIterator start,
InputIterator finish,
T init);
template <class InputIterator,
class T,
class BinaryOperation>
T accumulate(InputIterator start,
InputIterator finish,
T init,
BinaryOperation binary_op);
}
accumulate() applies a binary operation to init and each value in the range [start,finish). The result of each operation is returned in init. This process aggregates the result of performing the operation on every element of the sequence into a single value.
The accumulator acc is initialized with the value init and modified with acc = acc + *i or acc = binary_op(acc, *i) for each interator i, in order, in the range [start, finish).
accumulate() performs exactly finish-start applications of the binary operation, operator+ by default.
//
// accum.cpp
//
#include <numeric> // for accumulate
#include <vector> // for vector
#include <functional> // for multiplies
#include <iostream> // for cout
int main ()
{
// Typedef for convenience.
typedef std::vector<int, std::allocator<int> > vector;
// Initialize a vector using an array of integers.
const vector::value_type arr[] =
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
vector v1 (arr, arr + sizeof arr / sizeof *arr);
// Accumulate sums and products.
vector::value_type sum =
std::accumulate (v1.begin (), v1.end (), 0);
vector::value_type prod =
std::accumulate (v1.begin (), v1.end (), 1,
std::multiplies<vector::value_type>());
// Output the results.
std::cout << "For the series: ";
for (vector::iterator i = v1.begin (); i != v1.end (); ++i)
std::cout << *i << " ";
std::cout << "where N = " << v1.size ()
<< "\nThe sum = (N * N + N) / 2 = " << sum
<< "\nThe product = N! = " << prod << std::endl;
return 0;
}
Program Output:
For the series: 1 2 3 4 5 6 7 8 9 10 where N = 10
The sum = (N * N + N) / 2 = 55
The product = N! = 3628800
ISO/IEC 14882:1998 -- International Standard for Information Systems -- Programming Language C++, Section 26.4.1