C++11 Lambda 表达式详解:让你的代码更简洁高效

Lambda 表达式是 C++11 引入的一种用于定义匿名函数的方式。它们使得代码更加简洁和灵活,特别适用于需要将函数作为参数传递的场景,如标准库算法。本文将介绍 lambda 表达式的语法、使用方法和一些实际示例。

基本语法
[capture](parameters) -> return_type { body }
  • capture:捕获列表,指定哪些外部变量在 lambda 表达式中可用。可以按值或按引用捕获。
  • parameters:参数列表,与普通函数的参数列表相同。
  • return_type:返回类型,可选。如果省略,编译器会根据 body 推断返回类型。
  • body:函数体,包含要执行的代码。

示例

1. 最简单的 Lambda 表达式
auto lambda = []() { return 42; }; std::cout << lambda() << std::endl; // 输出 42
2. 带参数的 Lambda 表达式
auto add = [](int a, int b) { return a + b; }; std::cout << add(3, 4) << std::endl; // 输出 7
3. 指定返回类型的 Lambda 表达式
auto divide = [](int a, int b) -> double { return static_cast<double>(a) / b; }; std::cout << divide(10, 3) << std::endl; // 输出 3.33333

Lambda 表达式可以捕获其定义所在作用域的变量,这使得它们非常灵活。

4. 按值捕获
int x = 10; auto lambda = [x]() { return x + 5; }; std::cout << lambda() << std::endl; // 输出 15
5. 按引用捕获
int x = 10; auto lambda = [&x]() { x += 5; }; lambda(); std::cout << x << std::endl; // 输出 15
6. 捕获所有外部变量
  • 按值捕获所有外部变量
int x = 10, y = 20; auto lambda = [=]() { return x + y; }; std::cout << lambda() << std::endl; // 输出 30
  • 按引用捕获所有外部变量
int x = 10, y = 20; auto lambda = [&]() { x += y; }; lambda(); std::cout << x << std::endl; // 输出 30

使用 Lambda 表达式的实际例子

Lambda 表达式在标准库算法中非常有用。例如,我们可以用它来简化 std::sortstd::for_eachstd::remove_if 等函数的使用。

在算法中使用 Lambda 表达式
#include <algorithm>
#include <vector>
#include <iostream>

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    // 删除所有奇数
    v.erase(std::remove_if(v.begin(), v.end(), [](int n) { return n % 2 != 0; }), v.end());

    for (int n : v) {
        std::cout << n << " ";  // 输出 2 4 6 8 10
    }
    std::cout << std::endl;

    return 0;
}
自定义排序
#include <algorithm>
#include <vector>
#include <iostream>

int main() {
    std::vector<int> v = {5, 2, 9, 1, 5, 6};

    // 自定义排序:从大到小排序
    std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });

    for (int n : v) {
        std::cout << n << " ";  // 输出 9 6 5 5 2 1
    }
    std::cout << std::endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

落雨碎江南 Lucinda

如果您喜欢这篇文章欢迎打赏支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值