Lambda

本文介绍了C++11中引入的Lambda表达式的基本概念及其使用方式,通过多个示例展示了如何定义和使用Lambda表达式,并探讨了其背后的实现原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Lambda

1.概述

C++11 introduced lambdas,allowing the definition of inline functionality,which can be used as a parameter or a local object. Lambdas change the way the C++ standard library is used.

   A lambda is a definition of functionality that can be defined inside statements and expressions.Thus,you can use a lambdaas an inline function. The minimal lambda function has no parameters and simply does something.

    

[] {
    std::cout << "helllo lambda" << std::endl;
}();

auto I = [] {
    std::cout << "helllo lambda" << std::endl;
}();
I();

2.Lambda


3.代码示例

        int id = 0 ;

        auto f = [id]()mutable {
                cout << "id: " << id << endl;
                ++id;
        };
        id = 42;

        f();
        f();
        f();
        std::cout << id << std::endl;

        int id = 0 ;

        auto f = [&id]()mutable {
                cout << "id: " << id << endl;
                ++id;
        };
        id = 42;

        f();
        f();
        f();
        std::cout << id << std::endl;

        int id = 0 ;

        auto f = [id]() {
                cout << "id: " << id << endl;
                ++id;
        };
        id = 42;

        f();
        f();
        f();
        std::cout << id << std::endl;

        int id = 0;
        auto f2 = [id]() mutable ->int {
                cout << "id:" << id << endl;
                ++id;
                static int x = 5;
                int y = 6;
                return id;
        };
        id = 42;
        f2();
可以声明变量,可以返回数值

4.编译器生成

Here is what complier generates for lambda's

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

using namespace std;



class UnNamedLocalFunction {
private:
    int localVar;
public:
    UnNamedLocalFunction(int var) : localVar(var) {}
    bool operator() (int val) {
        return val == localVar;
    }   
};

int main() {
    int tobefound = 5;
    auto lambda1 = [tobefound] (int val) { return val == tobefound; };

    UnNamedLocalFunction lambda2(tobefound);
    bool b1 = lambda1(5);
    bool b2 = lambda2(5);
    
    std::cout << "b1: " << b1 << endl;
    std::cout << "b2: " << b2 << endl;


    return 0;
}

5.Lambda is an anonymous function object

The type of a lambda is an anonymous function object(or functor) that is unique for each lambda expression.Thus, todeclare objects of that type, you need templates or auto.If you need the type, you can usedecltype(), which is, for example, required to pass a lambdaas hash function or ordering or sorting criterion to associative or unordered containers.


6.定制STL表现


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值