lambda表达式

参考:
https://www.cnblogs.com/DswCnblog/p/5629165.html
https://en.cppreference.com/w/cpp/language/lambda

  • 完整格式:[ captures ] ( params ) specifiers exception attr -> ret { body }

    captures: 捕获列表
    params:传入参数
    specifiers: mutable, constexpr, consteval
    exception: 指定lambda可以throw的exception
    attr:函数的属性, 如[[ noreturn]], [[deprecated("because")]]
    ret:返回值
    body:函数体

  • 捕获列表:用于捕获lambda外部变量,可以按不同的方式捕获

    捕获方式说明
    [&]默认按引用捕获用到的变量(by reference)
    [=]默认按值捕获用到的变量(by copy)
    [this]按引用捕获当前对象
    [*this]按值捕获当前对象
    [&x]按引用方式捕获x变量
    [x]按值捕获x变量
    [=, &x]按引用捕获x变量,其余变量按值捕获
    [&, x]按值捕获x变量,其余变量按引用捕获
  • exception可以这样声明:

    https://visualstudiomagazine.com/articles/2012/06/18/cplus-lambda-expressions.aspx

    // 表明lambda可能throws runtime_error.
    auto myLambda = []() throws(runtime_error) -> bool { ... };
    
    // 表明lambda不会throw exceptions.
    auto myLambda = []() throws() -> bool { ... };
    
    // 表明lambda可能throw任何exception.
    auto myLambda = []() -> bool { ... };
    
  • 例子:
    vector中找某个符合条件的值,用find_if函数,其中第三个参数使用lambda表达式

    class A {
    	public:
    	A(std::string name): name_(name) {};
    	std::string name() { return name_; };
    	private:
    	std::string name_;
    };
    int main()
    {
    	std::vector<A> list;
    	list.emplace_back("xxx");
    	std::string value_to_find("xxx");
    	auto iter = std::find_if(list.begin(), list.end(),
    							 [value_to_find] (const A & obj) -> bool {
    							 	return obj.name() == value_to_find;
    							 });
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值