我开始学习一些C++,不明白高阶函数是如何在C++中工作的。在一个简单的例子中,有人能解释c++ 11高阶函数吗?我在网上找不到很多关于这个话题的信息。
发布于 2014-10-14 20:39:08
C++报头中的许多标准函数都是高阶函数的例子。
例如,count_if函数接受一个一元谓词,它是可调用函数的一种类型,并返回与给定谓词匹配的对象计数。因为count_if是一个函数,它接受另一个函数作为参数,这使得它成为一个高阶函数。
这个示例没有使用任何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;
}https://stackoverflow.com/questions/26369795
复制相似问题