stdaccumulate(3)
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
Type requirements
InputIt must meet the requirements of LegacyInputIterator.
T must meet the requirements of CopyAssignable and CopyConstructible.
Return value
- The sum of the given value and elements in the given range.
- 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
#include <iostream>
#include <vector>
#include <numeric>
#include <string>
#include <functional>
int main()
{
std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = std::accumulate(v.begin(), v.end(), 0);
int product = std::accumulate(v.begin(), v.end(), 1, std::multiplies<int>());
auto dash_fold = [](std::string a, int b) {
return std::move(a) + ‘-’ + std::to_string(b);
};
std::string s = std::accumulate(std::next(v.begin()), v.end(),
std::to_string(v[0]), // start with first element
dash_fold);
// Right fold using reverse iterators
std::string rs = std::accumulate(std::next(v.rbegin()), v.rend(),
std::to_string(v.back()), // start with last element
dash_fold);
std::cout << "sum: " << sum << ‘\n’
<< "product: " << product << ‘\n’
<< "dash-separated string: " << s << ‘\n’
<< "dash-separated string (right-folded): " << rs << ‘\n’;
}
Output:
See also