📜  C++中的Lambda表达式

📅  最后修改于: 2021-05-30 02:20:18             🧑  作者: Mango

C++ 11引入了lambda表达式,以允许我们编写一个内联函数,该函数可用于不会被重用且不值得命名的简短代码段。 lambda表达式可以以其最简单的形式定义如下:

[ capture clause ] (parameters) -> return-type  
{   
   definition of method   
} 

通常,lambda表达式中的return-type由编译器本身求值,我们不需要明确指定-> return-type部分可以忽略,但在某些复杂情况下(如条件语句),编译器无法确定返回值类型,我们需要指定。
下面给出了具有标准函数的lambda表达式的各种用法:

// C++ program to demonstrate lambda expression in C++
#include 
using namespace std;
  
// Function to print vector
void printVector(vector v)
{
    // lambda expression to print vector
    for_each(v.begin(), v.end(), [](int i)
    {
        std::cout << i << " ";
    });
    cout << endl;
}
  
int main()
{
    vector v {4, 1, 3, 5, 2, 3, 1, 7};
  
    printVector(v);
  
    // below snippet find first number greater than 4
    // find_if searches for an element for which
    // function(third argument) returns true
    vector:: iterator p = find_if(v.begin(), v.end(), [](int i)
    {
        return i > 4;
    });
    cout << "First number greater than 4 is : " << *p << endl;
  
  
    // function to sort vector, lambda expression is for sorting in
    // non-decreasing order Compiler can make out return type as
    // bool, but shown here just for explanation
    sort(v.begin(), v.end(), [](const int& a, const int& b) -> bool
    {
        return a > b;
    });
  
    printVector(v);
  
    // function to count numbers greater than or equal to 5
    int count_5 = count_if(v.begin(), v.end(), [](int a)
    {
        return (a >= 5);
    });
    cout << "The number of elements greater than or equal to 5 is : "
         << count_5 << endl;
  
    // function for removing duplicate element (after sorting all
    // duplicate comes together)
    p = unique(v.begin(), v.end(), [](int a, int b)
    {
        return a == b;
    });
  
    // resizing vector to make size equal to total different number
    v.resize(distance(v.begin(), p));
    printVector(v);
  
    // accumulate function accumulate the container on the basis of
    // function provided as third argument
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int f = accumulate(arr, arr + 10, 1, [](int i, int j)
    {
        return i * j;
    });
  
    cout << "Factorial of 10 is : " << f << endl;
  
    //     We can also access function by storing this into variable
    auto square = [](int i)
    {
        return i * i;
    };
  
    cout << "Square of 5 is : " << square(5) << endl;
}

输出:

4 1 3 5 2 3 1 7 
First number greater than 4 is : 5
7 5 4 3 3 2 1 1 
The number of elements greater than or equal to 5 is : 2
7 5 4 3 2 1 
Factorial of 10 is : 3628800
Square of 5 is : 25

通过访问封闭范围的变量,lambda表达式可以比普通函数具有更多函数。我们可以通过三种方式从封闭范围捕获外部变量:
通过引用捕获
按价值捕捉
两者捕获(混合捕获)

用于捕获变量的语法:
[&]:通过引用捕获所有外部变量
[=]:按值捕获所有外部变量
[a,&b]:按值捕获a,按引用捕获b

空捕获子句[]的lambda只能访问其本地变量。
捕获方式如下所示:

// C++ program to demonstrate lambda expression in C++
#include 
using namespace std;
  
int main()
{
    vector v1 = {3, 1, 7, 9};
    vector v2 = {10, 2, 7, 16, 9};
  
    //  access v1 and v2 by reference
    auto pushinto = [&] (int m)
    {
        v1.push_back(m);
        v2.push_back(m);
    };
  
    // it pushes 20 in both v1 and v2
    pushinto(20);
  
    // access v1 by copy
    [v1]()
    {
        for (auto p = v1.begin(); p != v1.end(); p++)
        {
            cout << *p << " ";
        }
    };
  
    int N = 5;
  
    // below snippet find first number greater than N
    // [N]  denotes,   can access only N by value
    vector:: iterator p = find_if(v1.begin(), v1.end(), [N](int i)
    {
        return i > N;
    });
  
    cout << "First number greater than 5 is : " << *p << endl;
  
    // function to count numbers greater than or equal to N
    // [=] denotes,   can access all variable
    int count_N = count_if(v1.begin(), v1.end(), [=](int a)
    {
        return (a >= N);
    });
  
    cout << "The number of elements greater than or equal to 5 is : "
         << count_N << endl;
}

输出:

First number greater than 5 is : 7
The number of elements greater than or equal to 5 is : 3

Lambda表达式只能在C++ 11和更高版本上使用。

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”