.\" ident @(#)accumulate.3 .\" Standard Template Library .\" $$RW_INSERT_HEADER "slyrs.man" .TH accumulate 3C++ "02 Apr 1998" "Rogue Wave Software" "-" .ce2 Standard C++ Library Copyright 1998, Rogue Wave Software, Inc. .SH NAME \f2accumulate\fP \ - Accumulates all elements within a range into a single value. .SH SYNOPSIS .RE .RS 0 #include .br template .br T accumulate (InputIterator first, .RE .RS 13 InputIterator last, .br T init); .RE .RS 0 .br template .RE .RS 0 T accumulate (InputIterator first, .RE .RS 13 InputIterator last, .br T init, .br BinaryOperation binary_op); .SH DESCRIPTION accumulate applies a binary operation to \f2init\fP and each value in the range \f2[first,last).\fP The result of each operation is returned in \f2init\fP. This process aggregates the result of performing the operation on every element of the sequence into a single value. Accumulation is done by initializing the accumulator \f2acc\fP with the initial value \f2init\fP and then modifying it with \f2acc = acc + *i \fPor \f2acc = binary_op(acc, *i)\fP for every iterator \f2i\fP in the range \f2[first, last)\fP in order. If the sequence is empty, accumulate returns \f2init\fP. \f2binary_op\fP should not have side effects. .SH COMPLEXITY accumulate performs exactly \f2last-first\fP applications of the binary operation (\f2operator+ \fPby default). .SH EXAMPLE .RE .RS 0 // .br // accum.cpp .br // .RE .RS 1 #include //for accumulate .br #include //for vector .br #include //for times .br #include .RE .RS 0 using namespace std; .br .br int main() .RE .RS 1 { .RE .RS 3 // .br //Typedef for vector iterators .br // .RE .RS 2 typedef vector::iterator iterator; .RE .RS 3 // .br //Initialize a vector using an array of ints .br // .RE .RS 2 int d1[10] = {1,2,3,4,5,6,7,8,9,10}; .br vector v1(d1, d1+10); .RE .RS 3 // .br //Accumulate sums and products .br // .RE .RS 2 int sum = accumulate(v1.begin(), v1.end(), 0); .br int prod = accumulate(v1.begin(), v1.end(), .RE .RS 14 1, times()); .RE .RS 3 // .br //Output the results .br // .RE .RS 2 cout << "For the series: "; .br for(iterator i = v1.begin(); i != v1.end(); i++) .RE .RS 6 cout << *i << " "; .RE .RS 0 .RE .RS 2 cout << " where N = 10." << endl; .br cout << "The sum = (N*N + N)/2 = " << sum << endl; .br cout << "The product = N! = " << prod << endl; .br return 0; .RE .RS 1 } .br .RE .RS 0 Program Output .RE .RS 0 .br For the series: 1 2 3 4 5 6 7 8 9 10 where N = 10. .br The sum = (N*N + N)/2 = 55 .br The product = N! = 3628800 .SH WARNINGS If your compiler does not support default template parameters, then you always need to supply the \f2Allocator\fP template argument. For instance, you have to write: .br vector > instead of: .br vector If your compiler does not support namespaces, then you do not need the using declaration for \f2std\fP.