.\" ident @(#)for_each.3 .\" Standard Template Library .\" $$RW_INSERT_HEADER "slyrs.man" .TH for_each 3C++ "02 Apr 1998" "Rogue Wave Software" "-" .ce2 Standard C++ Library Copyright 1998, Rogue Wave Software, Inc. .SH NAME \f2for_each\fP \ - Applies a function to each element in a range. .SH SYNOPSIS .br #include .br template .br void for_each(InputIterator first, InputIterator last, .RE .RS 14 Function f); .SH DESCRIPTION The for_each algorithm applies function \f2f\fP to all members of the sequence in the range \f2[first, last)\fP, where \f2first\fP and \f2last\fP are iterators that define the sequence. Since this a non-mutating algorithm, the function \f2f\fP cannot make any modifications to the sequence, but it can achieve results through side effects (such as copying or printing). If \f2f\fP returns a result, the result is ignored. .SH COMPLEXITY The function \f2f\fP is applied exactly \f2last - first\fP times. .SH EXAMPLE .RE .RS 0 // .br // for_each.cpp .br // .br #include .br #include .br #include .br #include .br using namespace std; .br .RE .RS 1 // Function class that outputs its argument times x .RE .RS 0 template .br class out_times_x : private unary_function .RE .RS 1 { .RE .RS 2 private: .RE .RS 5 Arg multiplier; .RE .RS 0 .RE .RS 2 public: .RE .RS 5 out_times_x(const Arg& x) : multiplier(x) { } .br void operator()(const Arg& x) .RE .RS 9 { cout << x * multiplier << " " << endl; } .RE .RS 1 }; .RE .RS 0 .br int main() .RE .RS 1 { .RE .RS 2 int sequence[5] = {1,2,3,4,5}; .RE .RS 0 .br .RE .RS 3 // Set up a vector .RE .RS 2 vector v(sequence,sequence + 5); .RE .RS 0 .RE .RS 3 .br // Setup a function object .RE .RS 2 out_times_x f2(2); .RE .RS 0 .RE .RS 3 for_each(v.begin(),v.end(),f2); // Apply function .RE .RS 0 .RE .RS 2 return 0; .RE .RS 1 } .br .RE .RS 0 Program Output .RE .RS 0 .br 2 .br 4 .br 6 .br 8 .br 10 .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: \f2vector >\fP instead of: \f2vector\fP If your compiler does not support namespaces, then you do not need the using declaration for \f2std\fP. .SH SEE ALSO Algorithms, Function_Objects