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); |
[first,last)
to init.
The behavior of this function template is equivalent to:
template <class InputIterator, class T> T accumulate (InputIterator first, InputIterator last, T init) { while (first!=last) { init = init + *first; // or: init=binary_op(init,*first) for the binary_op version ++first; } return init; }
[first,last)
, which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
[first,last)
.
// accumulate example #include <iostream> // std::cout #include <functional> // std::minus #include <numeric> // std::accumulate int myfunction (int x, int y) {return x+2*y;} struct myclass { int operator()(int x, int y) {return x+3*y;} } myobject; int main () { int init = 100; int numbers[] = {10,20,30}; std::cout << "using default accumulate: "; std::cout << std::accumulate(numbers,numbers+3,init); std::cout << '\n'; std::cout << "using functional's minus: "; std::cout << std::accumulate (numbers, numbers+3, init, std::minus<int>()); std::cout << '\n'; std::cout << "using custom function: "; std::cout << std::accumulate (numbers, numbers+3, init, myfunction); std::cout << '\n'; std::cout << "using custom object: "; std::cout << std::accumulate (numbers, numbers+3, init, myobject); std::cout << '\n'; return 0; }
Output:
using default accumulate: 160 using functional's minus: 40 using custom function: 220 using custom object: 280 |
[first,last)
are accessed (each element is accessed exactly once).
Note that invalid arguments cause undefined behavior.
http://www.cplusplus.com/reference/numeric/accumulate/?kw=accumulate