C++ lambda表达式详解

一、lambda表达式基本用法

1、语法

Lambda 表达式的基本语法如下:
捕获列表 mutable(可选) 异常属性 -> 返回类型
{
// 函数体
}

2、lambda值捕获

/**
 * @brief lamdba值捕获
 */
void test()
{
	int nvalue = 1;
	auto func_copyvalue = [nvalue]
	{
		return nvalue;
	};
	nvalue = 100;
	auto nValue = func_copyvalue();
	cout << "value:" << nValue << endl;
	// 这时, nValue == 1, 而 nvalue == 100.
	// 因为 func_copyvalue 在创建时就保存了一份 nvalue 的拷贝
}

3、lambda引用捕获

/**
 * @brief lamdba值捕获
 */
void test()
{
	int nvalue = 1;
	auto func_copyvalue = [&nvalue]
	{
		return nvalue;
	};
	nvalue = 100;
	auto nValue = func_copyvalue();
	cout << "value:" << nValue << endl;
	// 这时, nValue == 100, 而 nvalue == 100.
	// 因为 func_copyvalue 保存的是引用
}

4、lambda隐式捕获

/*
[] 空捕获列表
[name1, name2, ...] 捕获一系列变量
[&] 引用捕获, 让编译器自行推导引用列表
[=] 值捕获, 让编译器自行推导值捕获列表
*/
void test()
{
	// [] 空捕获列表
	auto func1 = [](int a) {return a; };

	// [name1, name2, ...] 捕获一系列变量
	int name1 = 1;
	int name2 = 2;
	int name3 = 3;
	auto func2 = [name1, name2, name3]() {return name1 + name2 + name3; };

	// [&] 引用捕获, 让编译器自行推导引用列表
	auto func3 = [&]() {return name1 + func1(1); };

	// [=] 值捕获, 让编译器自行推导值捕获列表
	auto func4 = [=]() {return name1; };
}

5、lambda表达式捕获

上面提到的值捕获、引用捕获都是已经在外层作用域声明的变量,因此这些捕获方式捕获的均为左值,而不能捕获右值。
C++14 给与了我们方便,允许捕获的成员用任意的表达式进行初始化,这就允许了右值的捕获, 被声明的捕获变量类型会根据表达式进行判断,判断方式与使用 auto 本质上是相同的

#include <memory>
#include <utility>
void test()
{
	auto important = std::make_unique<int>(1);
	auto add = [v1 = 1, v2 = std::move(important)](int x, int y)->int
	{
		return x + y + v1 + (*v2);
	};
	cout << add(3, 4) << endl;
}

6、泛型lambda

void test()
{
	auto add = [](auto x, auto y) {return x + y; };
	cout << add(3, 4) << endl;
	cout << add(1, 2) << endl;
	cout << add(1.1, 2.3) << endl;
}

二、lambda表达式与algorithm相结合使用(记录常用的)

1、std::sort

#include <algorithm>
#include <vector>
void test()
{
    std::vector<int> vec{1,3,5,2,4,7,9,8,10};
    std::sort(vec.begin(),vec.end(),
        [](int a, int b)
        {
            return a < b;
        });
}

2、std::for_each

#include <algorithm>
#include <vector>
void test()
{
    std::vector<int> vecTest{1,3,5,2,4,7,9,8,10};
    std::for_each(vecTest.begin(), vecTest.end(), 
        [](int n) 
        { 
            return n; 
        });
}

3、std::copy

#include <algorithm>
#include <vector>
void test()
{
    std::vector<int> m_Vec{1,3,5,2,4,7,9,8,10};
    std::copy(m_Vec.begin(), m_Vec.end(), ostream_iterator<int>(cout, " "));
}

4、std::function

#include <functional>
#include <map>
#include <string>
void test()
{
    std::map<std::string, std::function<int(int, int)>> op_dict = 
    {
        {"+", [](int x, int y)
              {
                      return x + y;
              }
        },
        {"-", [](int x, int y)
              {
                      return x - y;
              }
        },
        {"*", [](int x, int y)
              {
                      return x * y;
              }
        },
        {"/", [](int x, int y)
              {
                      return x / y;
              }
        },
    };
}

5、std::find_if

#include <algorithm>
#include <vector>
void test()
{
    std::vector<int> vec{ 1,2,3,5,3,7,9,5,10 };
    auto iter = std::find_if(vec.begin(), vec.end(),
        [](int a)
        {
            return a > 5;
        });
}

6、std::count_if

#include <algorithm>
#include <vector>
void test()
{
    std::vector<int> vec{ 1,2,3,5,3,7,9,5,10 };
    auto iter = std::count_if(vec.begin(), vec.end(),
        [](int a)
        {
            return a > 5;
        });
}

三、lambda在线程中使用

#include <thread>
#include <iostream>

using namespace std;

int main() 
{
    std::thread tthread001(
    [](int x)
    {
    	cout << x << endl;
    }
    , 100);
    tthread001.join();
    return 0;
}
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
C++ Lambda表达式是一种简洁的匿名表示方法,可以在代码中定义并使用。Lambda表达式的格式一般为:[] (参数列表) mutable -> 返回值类型 { 表达式 }。Lambda表达式可以捕获外部变量,并将其作为参数传递给函数体部分进行处理。Lambda表达式在使用时可以作为函数对象、函数指针或者函数参数进行传递。 Lambda表达式的底层原理是通过生成一个匿名类来实现。该类会重载函数调用运算符(),并包含Lambda表达式的函数体。Lambda表达式中捕获的外部变量会以成员变量的形式存储在该类中。当Lambda表达式被调用时,实际上是调用了该类的重载函数调用运算符()。 Lambda表达式可以与std::function结合使用,以实现函数对象的灵活使用。也可以将Lambda表达式赋值给相同类型的函数指针,实现函数指针的使用。但一般不建议这样使用,因为Lambda表达式已经提供了更加方便和简洁的方式。 总结来说,C++ Lambda表达式是一种用于定义匿名函数的语法,可以捕获外部变量并进行处理。其底层通过生成一个匿名类来实现,并提供了与std::function和函数指针的结合使用方式。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [C++11:lambda表达式](https://blog.csdn.net/zhang_si_hang/article/details/127117260)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值