zl程序教程

您现在的位置是:首页 >  后端

当前栏目

STL - C++ 11的Lambda表达式(上)

C++ 11 表达式 STL lambda
2023-09-11 14:16:56 时间

Lambda始自C++ 11,是一种在表达式或语句内指定函数行为的定义式。

你可以定义函数行为作为对象,以inline实参的形式传给算法作为predicate(判断式)。

eg:

std:transform(coll.begin(), coll.end(),  // source

                     coll.begin(),                 // destination

 

 

               

#include <algorithm>
#include <deque>
#include <iostream>
#include "LambdaTest.h"
#include "../../Core/ContainerUtil.h"

using namespace std;

deque<int> coll = { 1, 3, 19, 5, 13, 7, 11, 2, 17 };

cout << "all elements:" << endl;
ContainerUtil<deque<int>>::printElements(coll);

int x, y;
cout << "Input x: ";
cin >> x;
cout << endl;
cout << "Input y: ";
cin >> y;
cout << endl;
auto pos = find_if(coll.cbegin(), coll.cend(),  // range
    [=](int i) {                 // search criterion
    return i > x && i < y;
});

cout << "first elem >"<< x <<" and <"<< y <<": " << *pos << endl;

      [](double d) {          // lambda as function object

 

 

 

                       return d*d*d;

                     });

 

看个简单的例子:

findFirstInRange.cpp

 

运行结果:

all elements:   1  3  19  5  13  7  11  2  17

Input x: 5

Input y: 18

first elem >5 and <18: 13

 

注意点:

[=]

这个符号表明在lambda被声明时已有效的所有符号都以传值(by value)的形式传入lambda体内

[&]

这个符号表明在lambda被声明时已有效的所有符号都以传引用(by reference)的形式传入lambda体内

lambda内部可以改动他们的值

 

上面例子lambda的等价物

auto pos = find_if(coll.cbegin(), coll.cend(),  // range
    [=](int i) {                 // search criterion
    return i > x && i < y;
});

它等价于

1. 手写的循环

 

deque<int>::iterator pos;
for (pos = coll.begin;pos!=coll.end(); ++pos)
{
  if (*pos > x && *pos < y)
  {
     break;
  }
}

 

2. predicate(判断式)

 

bool pred(int I)
{
  return I > x && I < y;
}

...

pos = find_if(coll.begin(), coll.end(), pred);