Library: Algorithms
Function
Algorithm that applies a function to each element in a range
#include <algorithm> namespace std { template <class InputIterator, class Function> void Function for_each(InputIterator start, InputIterator finish, Function f); }
The for_each() algorithm applies the function object f to each value in the range [start, finish), where start and finish are iterators that define the sequence. Since this a non-mutating algorithm, the function f cannot make any modifications to the sequence, but it can achieve results through side effects (such as copying or printing). If f returns a result, the result is ignored.
for_each() returns the function object f.
The function object f is applied exactly finish - start times.
// // for_each.cpp // #include <algorithm> // for for_each #include <functional> // for less, unary_function #include <iostream> // for cout, endl #include <set> // for set // Function object that outputs its argument times x. template <class Arg> class out_times_x: public std::unary_function<Arg, void> { Arg multiplier; public: out_times_x(const Arg &x) : multiplier (x) { } void operator()(const Arg &x) const { std::cout << x * multiplier << " " << std::endl; } }; int main () { // Typedef for convenience. typedef std::set<int, std::less<int>, std::allocator<int> > sequence; sequence::value_type arr [] = { 1, 2, 3, 4, 5 }; // Populate a sequence from arr. sequence s(arr, arr + sizeof arr / sizeof *arr); // Construct a function object. out_times_x<sequence::value_type> f2(2); // Apply function object's operator() to each element. std::for_each(s.begin(), s.end(), f2); return 0; } Program Output
2 4 6 8 10
ISO/IEC 14882:1998 -- International Standard for Information Systems -- Programming Language C++, Section 25.1.1