Passing functions as arguments in C++
Using functions that take functions
There are times, when it is convenient to have a function receive a function as an argument. This technique can be seen in the standard C++ library. As an example, std::transform
can be used to create a series of values based on other values:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <vector>
#include <algorithm>
#include <iostream>
int makeNumbersBig(int small) {
return small * 10;
}
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
// Starting at numbers.begin() and until numbers.end(), execute
// makeNumbersBig and store the result in bigNumbers
std::transform(
numbers.begin(),
numbers.end(),
bigNumbers.begin(),
makeNumbersBig
);
// Print the values of bigNumbers
for (const auto big : bigNumbers) {
std::cout << big << std::endl;
}
}