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:
namespace std { Function for_each(InputIterator first, InputIterator last, Function); }
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:
std::cout << "leap years between 1990 and 1997 are: "; std::for_each(1990, 1997, print_if_leap); std::cout << std::endl;
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:
int vintageYears[] = {1947, 1955, 1960, 1967, 1994}; ... std::cout << "vintage years which were also leap years are: "; std::for_each(vintageYears, vintageYears + 5, print_if_leap); std::cout << std::endl;
Side effects need not be restricted to printing. Assume we have a function countCaps() that counts the occurrence of capital letters:
int capCount = 0; void countCaps(char c) { if (std::isupper(c)) capCount++; }
The following example counts the number of capital letters in a string value:
std::string advice = "Never Trust Anybody Over 30!"; std::for_each(advice.begin(), advice.end(),countCaps); std::cout << "upper-case letter count is " << capCount << std::endl;