Navigation: Up, Table of Contents, Bibliography, Index, Title Page

Function Objects

Function objects are objects with an operator()(..) defined. This results in faster code than passing function pointers, as the operator can even be inlined. The following function object classes are defined in \stl.

Arithmetic operations

#include <function.h>

\stl defines the following function object classes plus<T>, minus<T>, times<T>, divides<T>, and modulus<T>, which have an operator() with two arguments. Furthermore, there is the function object class negate<T> with a single argument. The arguments as well as the return value are of type T.

Pars pro toto we give the more formal definition for tha class plus<T>.

Example

The following example shows how the function object negate<T> is applied on each element of an array.

{
    const int n = 10;
    int A[n];
    A[0] = 23;
    ...
    A[9] = 56;
    for_each(A, A+n, negate<int>());
}

Comparisons

#include <function.h>

\stl defines the following function object classes equal_to<T>, not_equal_to<T>, greater<T>, less<T>, greater_equal<T>, less_equal<T>. They all have an operator() with two arguments of type T and the return value is of type bool.

Example

A set is a container that stores objects in a linear order. Instead of having global compare functions for a type we pass a function object as template argument. Set S stores integers in a decreasing order. The first template argument is the type of the data in the set, the second template argument is the type of the comparison function object class.

{
    set< int, greater<int> > S;
}

The following code fragment shows how to sort an array using the \stl function sort.

{
    const int n = 10;
    int A[n];
    A[0] = 23;
    ...
    A[9] = 56;
    sort(A, A+n, greater<int>());
}


Next chapter: Sequence Containers
Navigation: Up, Table of Contents, Bibliography, Index, Title Page
The CGAL Project. Mon, June 30, 1997.