Previous fileTop of DocumentContentsIndex pageNext file
Apache C++ Standard Library User's Guide

13.8 The for_each() Algorithm

The algorithm std::for_each() applies a function to all elements in a collection. This algorithm takes three arguments: the first two provide the iterators that describe the sequence to be evaluated, and the third is a one-argument function. The algorithm std::for_each() applies the function to each value of the sequence, passing the value as an argument:

For example, the following code fragment, which uses the print_if_leap() function, prints a list of the leap years that occur between 1900 and 1997:

The argument function is guaranteed to be invoked only once for each element in the sequence. The std::for_each() algorithm itself returns the value of the third argument, although this is usually ignored.

NOTE -- The function passed as the third argument is not permitted to make any modifications to the sequence, so it can only achieve a result by means of a side effect, such as printing, assigning a value to a global or static variable, or invoking another function that produces a side effect. If the argument function returns any result, it is ignored.

The following example searches an array of int values representing dates, to determine which vintage wine years were also leap years:

Side effects need not be restricted to printing. Assume we have a function countCaps() that counts the occurrence of capital letters:

The following example counts the number of capital letters in a string value:

Previous fileTop of DocumentContentsIndex pageNext file