C++的高阶函数

C++ higher order functions

本文关键字:函数 高阶 C++      更新时间:2023-10-16

我刚开始学习一些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表达式。