beautypg.com

Functions – HP Integrity NonStop H-Series User Manual

Page 38

background image

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

©Copyright 1996 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 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 words;
list counts;
...

This manual is related to the following products: