Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C
Expertise: Beginner
Dec 17, 2003



Building the Right Environment to Support AI, Machine Learning and Deep Learning

A Container for Pointers to Functions

Many times, you'll find you need to create a container for pointers to functions. The example below demonstrates the syntax for a vector of pointers to functions. For simplicity's sake, only one function, is_positive(double), has been defined. Notice how the vector of pointers to functions is declared, how the next pointer is added to the vector, and how an element of the vector is invoked using an iterator. The benefit of this technique is twofold: utilizing the power of the STL containers and the flexibility of pointers to functions.

bool is_positive(double a){ return a > 0.0;}
#include <iostream>
#include <vector>
int main(){
    std::vector<bool(*)(double)> fp;// declaration
    for( long i = 0; i < 10; ++i )
        fp.push_back(&is_positive);// adding
    std::vector<bool(*)(double)>::iterator it;
    double a = -4.0;
    for( it = fp.begin(); it != fp.end(); ++it )
             std::cout <<(*it)(a++)<< " ";//invocation
    std::cout << std::endl;
    return 0;
// the program output is "0 0 0 0 0 1 1 1 1 1"
Eugene Zak
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date