c++ how to take in a function as an argument code example
Example 1: 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};
std::vector<int> bigNumbers(3);
transform(
numbers.begin(),
numbers.end(),
bigNumbers.begin(),
[](int small) {
return small * 10;
}
);
for (const auto big : bigNumbers) {
std::cout << big << std::endl;
}
}
Example 2: passing function to another function in c++
1
2
3
int func (int)
int (*func) (int)
int (&func) (int)