C++11中Lambda的使用

it2026-09-01  2

C++11标准中新增了lambda函数

关于lambda函数,百度百科中的解释是这样的:

Lambda 表达式(lambda expression)是一个匿名函数,Lambda表达式基于数学中的λ演算得名,直接对应于其中的lambda抽象(lambda abstraction),是一个匿名函数,即没有函数名的函数。Lambda表达式可以表示闭包(注意和数学传统意义上的不同)。

在C++11前,为实现一个让奇数排在前面,偶数排在后面,并且从小到大排列的程序可能要这样写:

// 编译环境:MinGW-W64 8.1.0 #include <iostream> #include <algorithm> using namespace std; bool fun(const int &a, const int &b) { if ((a % 2 == 1) && (b % 2 == 0)) return true; if (a < b) return true; return false; } int main() { int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; sort(a, a + 10, fun); for (int i = 0; i < 10; i++) cout << a[i] << ' '; // 输出:1 3 5 7 9 2 4 6 8 10 return 0; }

可以看到,我们定义了一个函数fun并实现了这个排序,但真的有这个必要吗? C++11中的lambda就很好地解决了这一问题,我们先来看一段代码:

#include <iostream> using namespace std; int main() { auto f = [](int x){ return x * x; }; cout << f(20) << endl; return 0; }

我们用auto声明了一个变量f,并将一个长成这样的东西赋给了它:[](int x){ return x * x; } 这个就是lambda lambda的格式: [捕获列表](参数列表)mutable->类型{函数体} 其中:

格式内容捕获列表允许访问当前作用域下的某一个变量,可以为空(方括号不能省略)参数列表lambda函数的参数,可以省略(包括括号),不能有不定参数,不能有默认参数,参数必须有名称mutable捕获列表中的变量默认以const方式传递,不能修改,添加此关键字能指定变量可以被修改类型指定返回值类型(如果返回类型比较明显,可以省略,让编译器自动推断,省略时要连同箭头->一起省略),包括void类型函数体函数中要执行的代码,如果没有return语句且没指定类型,默认返回类型为void // 最短的lambda函数 []{}

所以,我们就可以用lambda来实现刚刚的sort里的比较函数

// 编译环境:MinGW-W64 8.1.0 #include <iostream> #include <algorithm> using namespace std; int main() { int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; sort(a, a + 10, [](const int &a, const int &b){ if ((a % 2 == 1) && (b % 2 == 0)) return true; if (a < b) return true; return false; }); for (int i = 0; i < 10; i++) cout << a[i] << ' '; // 输出:1 3 5 7 9 2 4 6 8 10 return 0; }

接下来是踩坑环节!

#include <iostream> using namespace std; int foo(int (*f)(int), int x) { return f(x); } int main() { cout << foo([](int a)->int{ return a * 5 + 7; }, 2) << endl; // 输出 17,一切正常 int Integer = 123; cout << foo([Integer](int a)->int{ return a * 5 + Integer; }, 2) << endl; // 编译错误 return 0; }

错误信息: 解决方法: 使用functional头文件的std::function类型 正确改法:

#include <iostream> #include <functional> using namespace std; int foo(function<int(int)> f, int x) { return f(x); } int main() { cout << foo([](int a)->int{ return a * 5 + 7; }, 2) << endl; // 输出 17 int Integer = 123; cout << foo([Integer](int a)->int{ return a * 5 + Integer; }, 2) << endl; // 输出 133 return 0; }
最新回复(0)