Lambda语法解析

一.Lambda语法

Lambda表达式是C++11标准引入的一种新特性,它是一种匿名函数,可以在需要时创建临时的函数对象,从而方便地进行函数式编程。

1.Lambda表达式基本形式:

[capture list](parameter list) -> return type { function body }

其中,capture list用于捕获变量,parameter list用于定义参数,return type用于定义返回值类型(可以省略),function body是函数体。

2.capture list(捕获列表)

在C++的lambda表达式中,捕获列表(capture list)用于控制lambda表达式的访问权限,也就是指定lambda表达式中的外部变量如何被访问。捕获列表由方括号[]括起来,其中包含一个逗号分隔的变量列表。

选项含义
[]不捕获任何变量,lambda表达式只能使用本地变量。
[&]按引用捕获所有外部变量,lambda表达式可以修改捕获的变量,且修改后的值将影响到外部作用域中的变量。
[=]按值捕获所有外部变量,lambda表达式不能修改捕获的变量,修改只会影响到lambda表达式内部的变量。
[var]按值捕获变量var,只有变量var会被捕获。
[&var]按引用捕获变量var,只有变量var会被捕获,且lambda表达式可以修改变量var的值。

3.捕获列表程序案例

#include <iostream>

int main() {
    int x = 10;
    int y = 20;

    // []:不捕获任何变量
    auto f1 = []() {
        std::cout << "Hello, world!" << std::endl;
    };
    f1();

    // [&]:按引用捕获所有外部变量
    auto f2 = [&]() {
        x++;
        y++;
        std::cout << "x = " << x << ", y = " << y << std::endl;
    };
    f2();
    std::cout << "x = " << x << ", y = " << y << std::endl;

    // [=]:按值捕获所有外部变量
    auto f3 = [=]() {
        std::cout << "x = " << x << ", y = " << y << std::endl;
    };
    f3();

    // [x]:按值捕获变量x
    auto f4 = [x]() {
        std::cout << "x = " << x << std::endl;
    };
    f4();

    // [&y]:按引用捕获变量y
    auto f5 = [&y]() {
        y++;
        std::cout << "y = " << y << std::endl;
    };
    f5();
    std::cout << "y = " << y << std::endl;

    return 0;
}

在这里插入图片描述

二.Lambda应用

1.使用 lambda 表达式对数组排序,并将排序后的元素存储到新数组中:

#include <iostream>
#include <algorithm>

using namespace std;

void print(int arr[],int n) {
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}
int main() {
    int arr[] = { 3, 6, 2, 7, 1, 9, 8, 4, 5 };
    int const n = sizeof(arr) / sizeof(arr[0]);
    sort(arr, arr + n, [](int a, int b) { return a < b; });
    print(arr, n);
    
    int sorted_arr[n];
    copy(arr, arr + n, sorted_arr);
    print(arr, n);

    return 0;
}

在这里插入图片描述

2.使用 lambda 表达式计算两个矩阵的和:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    vector<vector<int>> matrix1{ {1, 2}, {3, 4} };
    vector<vector<int>> matrix2{ {5, 6}, {7, 8} };

    vector<vector<int>> result(matrix1.size(), vector<int>(matrix1[0].size()));

    transform(matrix1.begin(), matrix1.end(), matrix2.begin(), result.begin(),
        [](const vector<int>& row1, const vector<int>& row2) {
            vector<int> row(row1.size());
            transform(row1.begin(), row1.end(), row2.begin(), row.begin(),
                [](int element1, int element2) { return element1 + element2; });
            return row;
        });

    for (const auto& row : result) {
        for (int element : row) {
            cout << element << " ";
        }
        cout << endl;
    }

    return 0;
}

在这里插入图片描述

3.使用 lambda 表达式实现自定义的 sort 函数,可以按照指定的排序规则排序:

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> words = { "apple", "banana", "pear", "orange" };

    // 按照字符串长度排序
    std::sort(words.begin(), words.end(), [](const std::string& a, const std::string& b) {
        return a.length() < b.length();
        });

    // 输出排序结果
    for (const auto& word : words) {
        std::cout << word << " ";
    }
    std::cout << std::endl;

    return 0;
}

在这里插入图片描述

4.使用 lambda 表达式实现一个类似于 filter 函数的功能,可以根据指定条件筛选出符合条件的元素:

#include <iostream>
#include <vector>
#include <algorithm>

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

    // 使用 lambda 表达式筛选出大于 5 的元素  //back_inserter:在末尾插入元素
    auto filtered = std::vector<int>{};
    std::copy_if(v.begin(), v.end(), std::back_inserter(filtered), [](int x) { return x > 5; });

    // 输出筛选后的结果
    std::cout << "Filtered elements: ";
    for (auto i : filtered) {
        std::cout << i << " ";
    }
    std::cout << std::endl;

    return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

LiuZuqiang_3027

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值