C++高阶函数

Ado*_*Ado 1 c++ function higher-order-functions

我开始学习一些C++并且不理解高阶函数在C++中是如何工作的.有人可以在一个简单的例子中解释更高阶的c ++ 11函数吗?我无法在网上找到有关此主题的更多信息.

b4h*_*and 5

<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;
}
Run Code Online (Sandbox Code Playgroud)

将此转换为使用某些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;
}
Run Code Online (Sandbox Code Playgroud)

在第二个例子中,我更改了向量初始化以使用列表初始化,并且我已经is_evenlambda表达式替换.

  • 它开始一个 lambda 表达式。 (2认同)