Top of document
©Copyright 1999 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;
 
 void countCaps(char c)  { if (isupper(c)) capCount++; }
 

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

   string advice = "Never Trust Anybody Over 30!";
    for_each(advice.begin(), advice.end(),countCaps);
    cout << "upper-case letter count is " << capCount << endl;
 

Top of document