C++:lambda表达式

在编程的过程中,一般通过函数指针或者函数对象(仿函数)来计算或者解决问题,如排序sort和移除操作remove_if的参数中都有相应的谓词函数。函数指针虽然语法开销小,但是不能在作用域内保持状态(can not retain state within a scope)。函数对象(仿函数)能够retain the state within a scope,但是有大的语法开销。
    lambda表达式能够综合二者的优点。能够减少代码量,同时不打乱程序的流程。
    lambda规范式如下:
     

capture 指定了在可见域范围内 lambda 表达式的代码内可见得外部变量的列表,具体解释如下:

  • [a,&b] a变量以值的方式被捕获,b以引用的方式被捕获。
  • [this] 以值的方式捕获 this 指针。
  • [&] 以引用的方式捕获所有的外部自动变量。
  • [=] 以值的方式捕获所有的外部自动变量
  • [] 不捕获外部的任何变量。
  Params为指定的参数,mutable申明以值捕获的变量的值能够被修改。

  exception 说明 lambda 表达式是否抛出异常(noexcept),以及抛出何种异常,类似于void f() throw(X, Y)。

  attribute 用来声明属性。

如使用lambda表达式对vector<int>对象求和:
      //use lambda expression for get the sum of vec
     int  sum = 0;
    for_each(vec.begin(), vec.end(), [&sum](  int  x)  /*mutable*/  {  return  sum += x;} );
    cout<<  "The sum of vec is:" <<sum<<endl;

定义一个auto变量来存放lambda表达式对象:
      auto  f1 = []( int  x,  int  y) {  return  x + y; };
    cout<<f1(3, 4)<<endl;
排序,
sort(vec.begin(), vec.end(), [](int x, int y) { return x < y; });

定义的同时实例化该lambda对象:
int n = [] (int x, int y) { return x + y; }(5, 4);
如何嵌套(nested) lambda expression:
int m = [](int x) 
      { return [](int y) { return y * 2; }(x) + 3; }(5);

高阶lambda表达式:
//test high order lambda expression
auto  g = [] ( int  x) -> function< int ( int )>
{        
return  [x]( int  y) {  return  x + y ;};
    };
auto  h = [] ( const  function<  int ( int )>& f,  int  z) {  return  f(z) + z;};
auto  result = h(g(45), 5);
 cout<< "The result of high order lb is :" <<result<<endl;
在类中调用lambda表达式并显示或隐式访问this指针:
class Scale
{
public:
   // The constructor.
   explicit Scale(int scale)
      : _scale(scale)
   {
   }

   // Prints the product of each element in a vector object 
   // and the scale value to the console.
   void ApplyScale(const vector<int>& v) const
   {
      for_each(v.begin(), v.end(), 
         [this](int n) { cout << n * this->_scale << endl; });
      //for_each(v.begin(), v.end(), 
          //[this](int n) { cout<<n*_scale<<endl;});
   }

private:
   int _scale;
};

 
      
给数组依次赋值:
int s[100];
int i = 0;
for_each(s, s + 100, [&i](int& x) { x = i++; });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Lambda表达式C++11引入的一种函数对象,可以在需要函数对象的地方使用,比如作为函数参数、返回值等。Lambda表达式的语法形式如下: ``` [capture list](parameters) mutable exception -> return type { // function body } ``` 其中,`capture list` 表示捕获列表,用于捕获外部变量。`parameters` 表示函数参数列表,`mutable` 用于表示是否可以修改值传递的变量,`exception` 是异常列表,`return type` 表示返回类型,`function body` 则是函数体。 在Lambda表达式中,可以通过 `[this]` 捕获当前对象的指针,即 `this` 指针,可以方便地访问当前对象的成员变量和成员函数。例如: ``` class MyClass { public: void foo() { int x = 1; auto lambda = [this, x]() mutable { this->m_member_var += x; this->m_member_function(); x++; }; lambda(); } private: int m_member_var; void m_member_function(); }; ``` 在上面的例子中,Lambda表达式通过 `[this, x]` 捕获了当前对象的指针和 `foo()` 函数中定义的变量 `x`。在 Lambda 表达式中可以通过 `this->m_member_var` 和 `this->m_member_function()` 访问当前对象的成员变量和成员函数。由于 `x` 是值传递的,所以在 Lambda 表达式中需要使用 `mutable` 关键字使其可修改,可以通过 `x++` 修改变量的值。最后调用 `lambda()` 执行 Lambda 表达式。 需要注意的是,Lambda表达式捕获 `this` 指针时,需要保证当前对象是有效的,即不能在已经销毁的对象中访问成员变量和成员函数。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值