function template
<numeric>
std::accumulate
sum (1) | template <class InputIterator, class T> T accumulate (InputIterator first, InputIterator last, T init); |
---|---|
custom (2) | template <class InputIterator, class T, class BinaryOperation> T accumulate (InputIterator first, InputIterator last, T init, BinaryOperation binary_op); |
Accumulate values in range
Returns the result of accumulating all the values in the range
[first,last)
to
init.
The default operation is to add the elements up, but a different operation can be specified as binary_op.
The behavior of this function template is equivalent to:
| |
Parameters
-
first, last
-
Input iterators to the initial and final positions in a sequence. The range used is
[first,last)
, which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
init
- Initial value for the accumulator. binary_op
-
Binary operation taking an element of type
T as first argument and an element in the range as second, and which returns a value that can be assigned to type
T.
This can either be a function pointer or a function object.
The operation shall not modify the elements passed as its arguments.
Return value
The result of accumulating init and all the elements in the range[first,last)
.
Example
| |
|
Output:
using default accumulate: 160 using functional's minus: 40 using custom function: 220 using custom object: 280 |
Complexity
Linear in the distance between first and last.Data races
The elements in the range[first,last)
are accessed (each element is accessed exactly once).
Exceptions
Throws if any of binary_op, the assignments or an operation on an iterator throws.Note that invalid arguments cause undefined behavior.