C++ lambda 匿名函数 C lambda 匿名函数什么是 lambda 表达式Lambda 表达式是 C11 引入的一种匿名函数语法允许我们在代码中直接定义函数对象而不必显式声明一个类或函数。它极大地简化了回调、算法和事件处理等场景的代码编写。Lambda 的基本语法如下cpp[capture](parameters) - return_type { body }其中-capture捕获列表定义如何从外部作用域访问变量-parameters参数列表-return_type返回类型可省略编译器可自动推导-body函数体## 基础示例最简单的 lambda让我们从一个最简单的 lambda 开始它不捕获任何外部变量只是执行一个简单的输出。cpp#include iostreamint main() { // 最简单的 lambda不捕获任何变量不接受参数无返回值 auto hello []() { std::cout Hello from lambda! std::endl; }; hello(); // 调用 lambda // 带参数的 lambda auto add [](int a, int b) - int { return a b; }; int result add(3, 4); std::cout 3 4 result std::endl; // 更简洁的写法自动推导返回类型 auto multiply [](int a, int b) { return a * b; }; std::cout 5 * 6 multiply(5, 6) std::endl; return 0;}输出Hello from lambda!3 4 75 * 6 30## 捕获机制详解Lambda 的捕获机制是它最强大的特性之一。通过捕获列表lambda 可以访问和使用定义它的作用域中的变量。cpp#include iostream#include vector#include algorithmint main() { // 值捕获 int x 10; int y 20; // 按值捕获 x 和 y auto sum [x, y]() { return x y; }; std::cout Sum with capture: sum() std::endl; // 输出 30 // 修改捕获的变量注意按值捕获的变量在 lambda 内部是 const 的 // 需要加上 mutable 关键字才能修改 auto mutable_capture [x]() mutable { x 5; // 现在可以修改了但只影响 lambda 内部的副本 return x; }; std::cout After mutable: mutable_capture() std::endl; // 输出 15 std::cout Outside x still: x std::endl; // 输出 10 // 引用捕获 int counter 0; auto increment [counter]() { counter; // 直接修改外部变量 }; increment(); increment(); increment(); std::cout Counter after 3 increments: counter std::endl; // 输出 3 // 混合捕获 int a 1, b 2, c 3; auto mixed [a, b, c]() { // a 是值捕获只读b 和 c 是引用捕获可修改 b a; c a; }; mixed(); std::cout a a , b b , c c std::endl; // a1, b3, c4 // 默认捕获 int val 42; auto capture_all_by_value []() { // [] 捕获所有外部变量为值 return val; }; auto capture_all_by_reference []() { // [] 捕获所有外部变量为引用 val 100; }; capture_all_by_reference(); std::cout After reference capture: val std::endl; // 输出 100 // 实际应用与 STL 算法配合 std::vectorint numbers {1, 5, 3, 8, 2, 7, 4}; int threshold 4; // 使用 lambda 作为谓词 auto count std::count_if(numbers.begin(), numbers.end(), [threshold](int n) { return n threshold; }); std::cout Numbers threshold : count std::endl; // 输出 3 // 使用 lambda 进行排序 std::vectorint to_sort {9, 3, 7, 1, 5}; std::sort(to_sort.begin(), to_sort.end(), [](int a, int b) { return a b; // 降序排序 }); std::cout Sorted descending: ; for (int n : to_sort) { std::cout n ; } std::cout std::endl; return 0;}## 高级用法泛型 lambda 与状态保持C14 引入了泛型 lambda允许使用 auto 参数类型。同时lambda 对象可以保持状态。cpp#include iostream#include functional#include vector#include algorithm#include stringint main() { // 泛型 lambda (C14) auto generic_lambda [](auto a, auto b) { return a b; }; std::cout Int addition: generic_lambda(10, 20) std::endl; // 输出 30 std::cout Double addition: generic_lambda(3.14, 2.86) std::endl; // 输出 6.0 std::cout String concatenation: generic_lambda(std::string(Hello ), World) std::endl; // 输出 Hello World // 保持状态的 lambda // 创建一个计数器每次调用递增 auto make_counter []() { int count 0; return [count]() mutable { return count; }; }; auto counter1 make_counter(); auto counter2 make_counter(); std::cout Counter1: ; for (int i 0; i 5; i) { std::cout counter1() ; // 输出 1 2 3 4 5 } std::cout std::endl; std::cout Counter2: ; for (int i 0; i 3; i) { std::cout counter2() ; // 输出 1 2 3 } std::cout std::endl; // 使用 std::function 存储 lambda std::functionint(int, int) func; func [](int a, int b) { return a b; }; std::cout Using std::function: func(10, 20) std::endl; // 可以替换为另一个 lambda func [](int a, int b) { return a * b; }; std::cout After reassignment: func(10, 20) std::endl; // 实际应用自定义比较器 std::vectorstd::string names {Alice, Bob, Charlie, David, Eve}; // 按字符串长度排序 std::sort(names.begin(), names.end(), [](const std::string a, const std::string b) { return a.length() b.length(); }); std::cout Sorted by length: ; for (const auto name : names) { std::cout name ; } std::cout std::endl; // 递归 lambda (使用 std::function) std::functionint(int) factorial [factorial](int n) - int { return n 1 ? 1 : n * factorial(n - 1); }; std::cout Factorial of 5: factorial(5) std::endl; // 输出 120 // 使用 lambda 进行延迟计算 auto lazy_add [](int a, int b) { return [a, b]() { return a b; }; }; auto delayed lazy_add(100, 200); // 此时还没有计算 std::cout Delayed computation: delayed() std::endl; // 输出 300 return 0;}## 性能与注意事项1.内联优化Lambda 本质上是函数对象编译器通常可以将其内联展开性能优于函数指针。2.捕获开销 - 值捕获复制变量可能产生开销 - 引用捕获没有复制开销但需要注意生命周期3.生命周期问题不要返回或存储引用捕获的 lambda 超出原始变量的生命周期。4.mutable 关键字只有在需要修改值捕获的变量时才使用 mutable。5.默认捕获谨慎使用[]和[]最好明确列出需要捕获的变量以提高代码可读性。## 总结C lambda 匿名函数是现代 C 编程中不可或缺的工具。它提供了-简洁性将函数定义和使用紧密耦合减少代码跳转-灵活性支持值捕获、引用捕获、默认捕获等多种方式-强大功能可以与 STL 算法、回调函数、事件处理等完美配合-性能优势编译器优化良好通常不会比手写函数对象差在实际开发中lambda 常用于- STL 算法的自定义操作排序、查找、变换等- 回调函数和事件处理器- 延迟计算和函数工厂- 替代短小的辅助函数掌握 lambda 是成为高效 C 开发者的重要一步。通过合理使用 lambda可以写出更清晰、更维护的代码。