C++的高阶函数
C++ higher order functions
我刚开始学习一些C++,不知道高阶函数在C++中是如何工作的。有人能用一个简单的例子解释一下c++11的高阶函数吗?我在网上找不到太多关于这个话题的信息。
<algorithm>
标头中的许多标准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;
}
在第二个示例中,我将向量初始化更改为使用列表初始化,并将is_even
替换为lambda表达式。
相关文章:
- C++高阶模板
- C++:实现一个接收lambda作为输入的高阶函数
- 调用 lambda 时出现分段错误,从 C++11 中的高阶函数返回
- C++无法派生高阶函数的模板参数
- 模板参数扣除/替换使用Lambda表达式使用高阶函数失败
- 使用std ::函数或转发引用作为高阶函数的通用对象输入参数
- 高阶沃罗诺伊图
- 创建高阶映射函数时,应该使用指针、引用或值
- 我可以使用来自不同类的函数参数创建一个高阶函数吗?
- 应用于数组的高阶函数
- 提升元函数类高阶函数
- 这两个高阶函数定义之间有什么区别吗?
- C++的高阶函数
- 大变量的高阶贝塞尔函数计算
- 具有模板的高阶函数
- 如何用c++模板模拟高阶函数
- C++中使用std::wcout的高阶函数失败,错误为C2248
- c++ 11中的高阶函数
- 可变高阶函数的重载分辨率
- C++0x中的高阶函数和lambda的问题