std::accumulate (3) - Linux Manuals
std::accumulate: std::accumulate
NAME
std::accumulate - std::accumulate
Synopsis
Defined in header <numeric>
template< class InputIt, class T > (1)
T accumulate( InputIt first, InputIt last, T init );
template< class InputIt, class T, class BinaryOperation >
T accumulate( InputIt first, InputIt last, T init, (2)
BinaryOperation op );
Computes the sum of the given value init and the elements in the range [first, last). The first version uses operator+ to sum up the elements, the second version uses the given binary function op
, both applying std::move to their operands on the left hand side
(since C++20).
op must not have side effects. (until C++11)
op must not invalidate any iterators, including the end iterators, nor modify any elements of the range involved, and also *last. (since C++11)
Parameters
first, last - the range of elements to sum
init - initial value of the sum
op - Ret fun(const Type1 &a, const Type2 &b);
Type requirements
-
InputIt must meet the requirements of LegacyInputIterator.
-
T must meet the requirements of CopyAssignable and CopyConstructible.
Return value
1) The sum of the given value and elements in the given range.
2) The result of left_fold of the given range over op
Notes
std::accumulate performs a left fold. In order to perform a right fold, one must reverse the order of the arguments to the binary operator, and use reverse iterators.
Possible implementation
First version
Second version
Example
// Run this code