Top of document
©Copyright 1999 Rogue Wave Software

Functions

A number of algorithms provided in the standard library require functions as arguments. A simple example is the algorithm for_each(), which invokes a function, passed as an argument, on each value held in a container. The following, for example, applies the printElement() function to produce output describing each element in a list of integer values:

void printElement (int value)
 {
    cout << "The list contains " << value << endl;
 }
 
 main () 
 {
    list<int> aList;
       ...
    for_each (aList.begin(), aList.end(), printElement);
 }

Binary functions take two arguments, and are often applied to values from two different sequences. For example, suppose we have a list of strings and a list of integers. For each element in the first list we wish to replicate the string the number of times given by the corresponding value in the second list. We could perform this easily using the function transform() from the standard library. First, we define a binary function with the desired characteristics:

string stringRepeat (const string & base, int number)
                     // replicate base the given number of times
 {
    string result;   // initially the result is empty
    while (number--)  result += base;
    return result;
 }
 

The following call on transform() then produces the desired effect:

list<string> words;
 list<int> counts;
    ...
 transform (words.begin(), words.end(), 
    counts.begin(), words.begin(), stringRepeat);
 

Transforming the words one, two, three with the values 3, 2, 3 would yield the result oneoneone, twotwo, threethreethree.


Top of document