<algorithm> 标头中的许多标准 C++ 函数都是高阶函数的示例。
例如,count_if 函数采用一元谓词,它是一种可调用函数,并返回与给定谓词匹配的对象计数。由于count_if 是一个将另一个函数作为参数的函数,因此它成为higher-order function。
此示例未使用任何 C++11 功能,但 C++11 只是增强了以前 C++ 标准中对高阶函数的现有支持:
#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;
}
将其转换为使用某些 C++11 功能的示例相当简单:
#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;
}
在第二个示例中,我将向量初始化更改为使用list initialization,并将is_even 替换为lambda expression。