pass function as argument C++ code example

Example 1: passing a function as an argument in c

void func ( void (*f)(int) ) {
  for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
    (*f)(ctr);
  }
}

Example 2: passing function to another function in c++

#include <vector>
#include <algorithm>
#include <iostream>

void transform(std::vector<int>::iterator beginIt,
    std::vector<int>::iterator endIt,
    std::vector<int>::iterator destinationBeginIt,
    int func (int)) {
  while (beginIt != endIt) {
    *destinationBeginIt = func(*beginIt);
    beginIt++;
    destinationBeginIt++;
  }
}

int main() {
  std::vector<int> numbers{1, 2, 3}; // numbers has 3 values: 1, 2, 3
  std::vector<int> bigNumbers(3); // bigNumbers has 3 values, default
                                  // initialized: 0, 0, 0

  transform(
    numbers.begin(),
    numbers.end(),
    bigNumbers.begin(),
    [](int small) {
      return small * 10;
    }
  );

  // Print the values of bigNumbers
  for (const auto big : bigNumbers) {
    std::cout << big << std::endl;
  }
}

Example 3: passing function to another function in c++

1
2
3
int func (int)
int (*func) (int)
int (&func) (int)

Example 4: c++ how to make function as argument

void func ( void (*f)(int) );

Tags:

C Example