C++ Passing Functions to Functions

‮figi.www‬tidea.com

In C++, you can pass a function as an argument to another function. This can be useful when you want to pass a function to a generic algorithm or when you want to apply a specific function to every element in a container.

Here's an example of how to pass a function to another function:

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

void print_vector(const std::vector<int>& vec) {
    for (int value : vec) {
        std::cout << value << " ";
    }
    std::cout << std::endl;
}

void apply_function_to_vector(std::vector<int>& vec, void (*func)(int&)) {
    for (int& value : vec) {
        func(value);
    }
}

void square(int& value) {
    value = value * value;
}

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    print_vector(vec);
    
    apply_function_to_vector(vec, square);
    print_vector(vec);
    
    return 0;
}

In this example, we define a function called apply_function_to_vector that takes two arguments: a reference to a vector of integers, and a function pointer to a function that takes an integer reference as an argument and returns void. The function apply_function_to_vector applies the given function to each element in the vector.

We also define a function called square that squares its input argument by multiplying it by itself. We pass the square function as an argument to apply_function_to_vector to apply it to each element in the vector.

When we run the program, it prints the original vector, applies the square function to each element in the vector, and then prints the resulting vector.

Passing functions to functions can be a powerful technique in C++, allowing you to write generic code that can be used with different functions. You can also use C++ lambda expressions as a more flexible and expressive way of passing functions as arguments.