C++高阶函数

3

我开始学习一些C++,不明白在C++中高阶函数如何工作。有人可以用一个简单的例子解释C++ 11中的高阶函数吗?我在网上找不到太多关于这个主题的信息。


1
“Higher order”?在什么上下文中,例如多项式?你能举个例子吗? - Cory Kramer
1
高阶函数是指接受函数作为参数或返回函数的函数。在C++中,这可以是任何可调用对象(std::function、函数指针、lambda表达式、函数对象等实现了operator()的对象)。 - user703016
2
第五个谷歌搜索结果:http://programmers.stackexchange.com/questions/170464/c11-support-for-higher-order-list-functions - Neil Kirk
1个回答

8
许多<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表达式

在你的例子中,你将可调用函数iseven()的定义切换为[](int i) -> bool { return i % 2 == 0; },这里的[]有什么用处(C++11标准)? - Anu
2
它开始一个lambda表达式。 - b4hand

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接