beautypg.com

Miscellaneous algorithms, Apply a function to all elements in a collection, The algorithm for_each() – HP Integrity NonStop H-Series User Manual

Page 176: Section 13, Apply a function to all elements, Will apply a function to every, Apply a function to all elements in a, Collection

background image

Click on the banner to return to the user guide home page.

©Copyright 1996 Rogue Wave Software

Miscellaneous Algorithms

In the final section we describe the remaining algorithms found in the standard library.

Apply a Function to All Elements in a Collection

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

Function for_each
(InputIterator first, InputIterator last, Function);

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

cout << "leap years between 1990 and 1997 are: ";
for_each (1990, 1997, print_if_leap);
cout << endl;

Results Produced by Side Effect

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

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

int vintageYears[] = {1947, 1955, 1960, 1967, 1994};
...

cout << "vintage years which were also leap years are: ";
for_each (vintageYears, vintageYears + 5, print_if_leap);
cout << 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;

This manual is related to the following products: