lambda表达式(匿名函数)的简单使用

1.简介

中文名匿名函数

lambda的存在可以让你在函数里面写函数

其形式为

[](){}

一个简单的例子

下面是一个不可以使用外部变量,没有确切返回类型的lambda表达式用在了sort里代替了cmp()

sort(points.begin(), points.end(), [](Point a, Point b) {
    return a.y < b.y; 
});

下面是一个有名字的可以使用外部变量的有明确返回类型的lambda表达式

bool ok = false;
auto fun = [&](vector<int> &nums) -> void {
  nums.clear(); 
  ok = true;
};

2.参数类型

[]

部分为要捕获的外部变量

我们只需要简单的知道

  • [&] 可以使用和修改

  • [=] 可以使用但不可以修改

  • [] 不可以使用

()

为labmda参数,实际相当于函数参数

{}

相当于函数正文

除此之外

auto fun1 = []() -> int {};
auto fun2 = []() -> bool {};

可以指定函数返回类型

3.在ACM中的使用

1)在sort()中代替cmp函数或者重载运算符

对于需要多次按不同规则的排序很好用

sort(points.begin(), points.end(), [](array<int, 3> a, array<int, 3> b) {
    return a[2] < b[2]; 
});

2)和function结合写函数内的函数

void solution()
{
    cin >> n;
    queue<int> Q;
    M.clear();
    int tot = 0;
    int cnt = 0;
    ok = true;
    for (int i = 1; i <= n; i++)
    {
        int tmp;
        cin >> tmp;
        tot += tmp;
        M[tmp]++;
    }
    function<void(int)> dfs = [&](int nowNum) -> void {
        if (!ok)
            return;
        if (M[nowNum])
        {
            M[nowNum]--;
            return;
        }
        if (nowNum >= 2)
        {
            dfs(nowNum / 2);
            dfs((nowNum + 1) / 2);
        }
        else
            ok = false;
    };
    dfs(tot);
    for (auto it : M)
        if (it.second)
            ok = false;
    if (ok)
        cout << "YES" << endl;
    else
        cout << "NO" << endl;
}

这里需要注意的是,类型不能再写成auto,需要指定函数类型

function<type1(type2,type3)> fun = [](type2 arg1,type3 arg2){};

// 相当于

type1 fun(type2 arg1, type3 arg2) {};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Abmcar

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

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

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

打赏作者

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

抵扣说明:

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

余额充值