Wednesday, January 11, 2012

Using Functions as Algorithm Arguments

Examples of Using Functions as Algorithm Arguments:

The simplest example is the for_each() algorithm. It calls a user-defined function for each
element of the specified range. Consider the following example:

Example :

The for_each() algorithm calls the passed print() function for every element in the range [coll.begin(),coll.end()). Thus, the output of the program is as follows:
1 2 3 4 5 6 7 8 9
Algorithms use auxiliary functions in several variants—some optional, some mandatory. In particular, you can use them to specify a search criterion, a sorting criterion, or to define a manipulation while transferring elements from one collection to another.

Here is another example program:

In this example, square() is used to square each element of coll1 while it is transformed to coll2 (Figure below). The program has the following output:

Figure: How transform() Operates

initialized: 1 2 3 4 5 6 7 8 9
squared: 1 4 9 16 25 36 49 64 81

See Also:

No comments:

Post a Comment