I a started learning some C++ and don't understand how higher order functions work in C++. Can someone explain c++ 11 functions of higher order on a simple example? I can't find much information on this topic anywhere online.
Many of the standard C++ functions in the <algorithm>
header are examples of higher-order functions.
For example the count_if
function takes a unary predicate which is a type of callable function and returns a count of objects that match the given predicate. Since count_if
is a function which takes another function as an argument, this makes it a higher-order function.
This example doesn't make use of any C++11 features, but C++11 just augments the existing support for higher-order functions in previous C++ standards:
#include <algorithm>
#include <iostream>
#include <vector>
bool is_even(int i) {
return i % 2 == 0;
}
int main(int argc, char *argv[]) {
std::vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i);
}
std::cout
<< "count = "
<< std::count_if(v.begin(), v.end(), &is_even)
<< std::endl;
return 0;
}
Converting this into an example that uses some C++11 features is fairly trivial:
#include <algorithm>
#include <iostream>
#include <vector>
int main(int argc, char *argv[]) {
std::vector<int> v = { 0, 1, 2, 3, 4, 5 };
std::cout
<< "count = "
<< std::count_if(v.begin(),
v.end(),
[](int i) -> bool { return i % 2 == 0; })
<< std::endl;
return 0;
}
In the second example, I changed the vector initialization to use list initialization, and I've replaced is_even
with a lambda expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With