Lambda 表达式的示例

本文深入探讨了C++中Lambda表达式的应用,包括声明、调用、嵌套、方法内使用以及与STL算法的结合。通过多个示例,详细解释了Lambda表达式的语法、作用域规则、捕获机制以及它们在不同场景下的优势。

示例 1

由于 lambda 表达式已类型化,所以你可以将其指派给 auto 变量或 function 对象,如下所示:

Dd293599.collapse_all(zh-cn,VS.120).gif代码

// declaring_lambda_expressions1.cpp
// compile with: /EHsc /W4
#include <functional>
#include <iostream>

int main()
{

    using namespace std;

    // Assign the lambda expression that adds two numbers to an auto variable.
    auto f1 = [](int x, int y) { return x + y; };

    cout << f1(2, 3) << endl;

    // Assign the same lambda expression to a function object.
    function<int(int, int)> f2 = [](int x, int y) { return x + y; };

    cout << f2(3, 4) << endl;
}

Dd293599.collapse_all(zh-cn,VS.120).gif输出

5
7

代码

// declaring_lambda_expressions2.cpp
// compile with: /EHsc /W4
#include <functional>
#include <iostream>

int main()
{
   using namespace std;

   int i = 3;
   int j = 5;

   // The following lambda expression captures i by value and
   // j by reference.
   function<int (void)> f = [i, &j] { return i + j; };

   // Change the values of i and j.
   i = 22;
   j = 44;

   // Call f and print its result.
   cout << f() << endl;
}

Dd293599.collapse_all(zh-cn,VS.120).gif输出

47


调用 Lambda 表达式

你可以立即调用 lambda 表达式,如下面的代码片段所示。 第二个代码片段演示如何将 lambda 作为参数传递给标准模板库 (STL) 算法,例如 find_if

Dd293599.collapse_all(zh-cn,VS.120).gif示例 1

以下示例声明的 lambda 表达式将返回两个整数的总和并使用参数54立即调用该表达式:

Dd293599.collapse_all(zh-cn,VS.120).gif代码

// calling_lambda_expressions1.cpp
// compile with: /EHsc
#include <iostream>

int main()
{
   using namespace std;
   int n = [] (int x, int y) { return x + y; }(5, 4);
   cout << n << endl;
}

Dd293599.collapse_all(zh-cn,VS.120).gif输出

9

Dd293599.collapse_all(zh-cn,VS.120).gif示例 2

以下示例将 lambda 表达式作为参数传递给 find_if 函数。 如果 lambda 表达式的参数是偶数,则返回 true

Dd293599.collapse_all(zh-cn,VS.120).gif代码

// calling_lambda_expressions2.cpp
// compile with: /EHsc /W4
#include <list>
#include <algorithm>
#include <iostream>

int main()
{
    using namespace std;

    // Create a list of integers with a few initial elements.
    list<int> numbers;
    numbers.push_back(13);
    numbers.push_back(17);
    numbers.push_back(42);
    numbers.push_back(46);
    numbers.push_back(99);

    // Use the find_if function and a lambda expression to find the 
    // first even number in the list.
    const list<int>::const_iterator result = 
        find_if(numbers.begin(), numbers.end(),[](int n) { return (n % 2) == 0; });

    // Print the result.
    if (result != numbers.end()) {
        cout << "The first even number in the list is " << *result << "." << endl;
    } else {
        cout << "The list contains no even numbers." << endl;
    }
}

Dd293599.collapse_all(zh-cn,VS.120).gif输出

The first even number in the list is 42.
调用 Lambda 表达式

你可以立即调用 lambda 表达式,如下面的代码片段所示。 第二个代码片段演示如何将 lambda 作为参数传递给标准模板库 (STL) 算法,例如 find_if

Dd293599.collapse_all(zh-cn,VS.120).gif示例 1

以下示例声明的 lambda 表达式将返回两个整数的总和并使用参数54立即调用该表达式:

Dd293599.collapse_all(zh-cn,VS.120).gif代码

// calling_lambda_expressions1.cpp
// compile with: /EHsc
#include <iostream>

int main()
{
   using namespace std;
   int n = [] (int x, int y) { return x + y; }(5, 4);
   cout << n << endl;
}

Dd293599.collapse_all(zh-cn,VS.120).gif输出

9

Dd293599.collapse_all(zh-cn,VS.120).gif示例 2

以下示例将 lambda 表达式作为参数传递给 find_if 函数。 如果 lambda 表达式的参数是偶数,则返回 true

Dd293599.collapse_all(zh-cn,VS.120).gif代码

// calling_lambda_expressions2.cpp
// compile with: /EHsc /W4
#include <list>
#include <algorithm>
#include <iostream>

int main()
{
    using namespace std;

    // Create a list of integers with a few initial elements.
    list<int> numbers;
    numbers.push_back(13);
    numbers.push_back(17);
    numbers.push_back(42);
    numbers.push_back(46);
    numbers.push_back(99);

    // Use the find_if function and a lambda expression to find the 
    // first even number in the list.
    const list<int>::const_iterator result = 
        find_if(numbers.begin(), numbers.end(),[](int n) { return (n % 2) == 0; });

    // Print the result.
    if (result != numbers.end()) {
        cout << "The first even number in the list is " << *result << "." << endl;
    } else {
        cout << "The list contains no even numbers." << endl;
    }
}

Dd293599.collapse_all(zh-cn,VS.120).gif输出

The first even number in the list is 42.



嵌套 Lambda 表达式

Dd293599.collapse_all(zh-cn,VS.120).gif示例

你可以将 lambda 表达式嵌套在另一个中,如下例所示。 内部 lambda 表达式将其参数与 2 相乘并返回结果。 外部 lambda 表达式通过其参数调用内部 lambda 表达式并在结果上加 3。

Dd293599.collapse_all(zh-cn,VS.120).gif代码

// nesting_lambda_expressions.cpp
// compile with: /EHsc /W4
#include <iostream>

int main()
{
    using namespace std;

    // The following lambda expression contains a nested lambda
    // expression.
    int timestwoplusthree = [](int x) { return [](int y) { return y * 2; }(x) + 3; }(5);

    // Print the result.
    cout << timestwoplusthree << endl;
}

Dd293599.collapse_all(zh-cn,VS.120).gif输出

13
调用 Lambda 表达式

你可以立即调用 lambda 表达式,如下面的代码片段所示。 第二个代码片段演示如何将 lambda 作为参数传递给标准模板库 (STL) 算法,例如 find_if

Dd293599.collapse_all(zh-cn,VS.120).gif示例 1

以下示例声明的 lambda 表达式将返回两个整数的总和并使用参数54立即调用该表达式:

Dd293599.collapse_all(zh-cn,VS.120).gif代码

// calling_lambda_expressions1.cpp
// compile with: /EHsc
#include <iostream>

int main()
{
   using namespace std;
   int n = [] (int x, int y) { return x + y; }(5, 4);
   cout << n << endl;
}

Dd293599.collapse_all(zh-cn,VS.120).gif输出

9

Dd293599.collapse_all(zh-cn,VS.120).gif示例 2

以下示例将 lambda 表达式作为参数传递给 find_if 函数。 如果 lambda 表达式的参数是偶数,则返回 true

Dd293599.collapse_all(zh-cn,VS.120).gif代码

// calling_lambda_expressions2.cpp
// compile with: /EHsc /W4
#include <list>
#include <algorithm>
#include <iostream>

int main()
{
    using namespace std;

    // Create a list of integers with a few initial elements.
    list<int> numbers;
    numbers.push_back(13);
    numbers.push_back(17);
    numbers.push_back(42);
    numbers.push_back(46);
    numbers.push_back(99);

    // Use the find_if function and a lambda expression to find the 
    // first even number in the list.
    const list<int>::const_iterator result = 
        find_if(numbers.begin(), numbers.end(),[](int n) { return (n % 2) == 0; });

    // Print the result.
    if (result != numbers.end()) {
        cout << "The first even number in the list is " << *result << "." << endl;
    } else {
        cout << "The list contains no even numbers." << endl;
    }
}

Dd293599.collapse_all(zh-cn,VS.120).gif输出

The first even number in the list is 42.

嵌套 Lambda 表达式

Dd293599.collapse_all(zh-cn,VS.120).gif示例

你可以将 lambda 表达式嵌套在另一个中,如下例所示。 内部 lambda 表达式将其参数与 2 相乘并返回结果。 外部 lambda 表达式通过其参数调用内部 lambda 表达式并在结果上加 3。

Dd293599.collapse_all(zh-cn,VS.120).gif代码

// nesting_lambda_expressions.cpp
// compile with: /EHsc /W4
#include <iostream>

int main()
{
    using namespace std;

    // The following lambda expression contains a nested lambda
    // expression.
    int timestwoplusthree = [](int x) { return [](int y) { return y * 2; }(x) + 3; }(5);

    // Print the result.
    cout << timestwoplusthree << endl;
}

Dd293599.collapse_all(zh-cn,VS.120).gif输出

13



在方法中使用 Lambda 表达式

Dd293599.collapse_all(zh-cn,VS.120).gif示例

你可以在方法的主体中使用 lambda 表达式。 lambda 表达式可以访问该封闭方法可访问的任何方法或数据成员。 你可以显式或隐式捕获 this 指针,以提供对封闭类的方法和数据成员的访问路径。

你可以在方法中显式使用 this 指针,如下所示:

void ApplyScale(const vector<int>& v) const
{
   for_each(v.begin(), v.end(), 
      [this](int n) { cout << n * _scale << endl; });
}

你也可以隐式捕获 this 指针:

void ApplyScale(const vector<int>& v) const
{
   for_each(v.begin(), v.end(), 
      [=](int n) { cout << n * _scale << endl; });
}

以下示例显示封装小数位数值的Scale类。

调用 Lambda 表达式

你可以立即调用 lambda 表达式,如下面的代码片段所示。 第二个代码片段演示如何将 lambda 作为参数传递给标准模板库 (STL) 算法,例如 find_if

Dd293599.collapse_all(zh-cn,VS.120).gif示例 1

以下示例声明的 lambda 表达式将返回两个整数的总和并使用参数54立即调用该表达式:

Dd293599.collapse_all(zh-cn,VS.120).gif代码

// calling_lambda_expressions1.cpp
// compile with: /EHsc
#include <iostream>

int main()
{
   using namespace std;
   int n = [] (int x, int y) { return x + y; }(5, 4);
   cout << n << endl;
}

Dd293599.collapse_all(zh-cn,VS.120).gif输出

9

Dd293599.collapse_all(zh-cn,VS.120).gif示例 2

以下示例将 lambda 表达式作为参数传递给 find_if 函数。 如果 lambda 表达式的参数是偶数,则返回 true

Dd293599.collapse_all(zh-cn,VS.120).gif代码

// calling_lambda_expressions2.cpp
// compile with: /EHsc /W4
#include <list>
#include <algorithm>
#include <iostream>

int main()
{
    using namespace std;

    // Create a list of integers with a few initial elements.
    list<int> numbers;
    numbers.push_back(13);
    numbers.push_back(17);
    numbers.push_back(42);
    numbers.push_back(46);
    numbers.push_back(99);

    // Use the find_if function and a lambda expression to find the 
    // first even number in the list.
    const list<int>::const_iterator result = 
        find_if(numbers.begin(), numbers.end(),[](int n) { return (n % 2) == 0; });

    // Print the result.
    if (result != numbers.end()) {
        cout << "The first even number in the list is " << *result << "." << endl;
    } else {
        cout << "The list contains no even numbers." << endl;
    }
}

Dd293599.collapse_all(zh-cn,VS.120).gif输出

The first even number in the list is 42.

嵌套 Lambda 表达式

Dd293599.collapse_all(zh-cn,VS.120).gif示例

你可以将 lambda 表达式嵌套在另一个中,如下例所示。 内部 lambda 表达式将其参数与 2 相乘并返回结果。 外部 lambda 表达式通过其参数调用内部 lambda 表达式并在结果上加 3。

Dd293599.collapse_all(zh-cn,VS.120).gif代码

// nesting_lambda_expressions.cpp
// compile with: /EHsc /W4
#include <iostream>

int main()
{
    using namespace std;

    // The following lambda expression contains a nested lambda
    // expression.
    int timestwoplusthree = [](int x) { return [](int y) { return y * 2; }(x) + 3; }(5);

    // Print the result.
    cout << timestwoplusthree << endl;
}

Dd293599.collapse_all(zh-cn,VS.120).gif输出

13

在方法中使用 Lambda 表达式

Dd293599.collapse_all(zh-cn,VS.120).gif示例

你可以在方法的主体中使用 lambda 表达式。 lambda 表达式可以访问该封闭方法可访问的任何方法或数据成员。 你可以显式或隐式捕获 this 指针,以提供对封闭类的方法和数据成员的访问路径。

你可以在方法中显式使用 this 指针,如下所示:

void ApplyScale(const vector<int>& v) const
{
   for_each(v.begin(), v.end(), 
      [this](int n) { cout << n * _scale << endl; });
}

你也可以隐式捕获 this 指针:

void ApplyScale(const vector<int>& v) const
{
   for_each(v.begin(), v.end(), 
      [=](int n) { cout << n * _scale << endl; });
}

以下示例显示封装小数位数值的Scale类。


// method_lambda_expression.cpp
// compile with: /EHsc /W4
#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

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(), [=](int n) { cout << n * _scale << endl; });
    }

private:
    int _scale;
};

int main()
{
    vector<int> values;
    values.push_back(1);
    values.push_back(2);
    values.push_back(3);
    values.push_back(4);

    // Create a Scale object that scales elements by 3 and apply
    // it to the vector object. Does not modify the vector.
    Scale s(3);
    s.ApplyScale(values);
}

Dd293599.collapse_all(zh-cn,VS.120).gif输出

3
6
9
12

Dd293599.collapse_all(zh-cn,VS.120).gif备注

ApplyScale方法使用 lambda 表达式打印小数位数值与 vector 对象中的每个元素的乘积。 lambda 表达式隐式捕获 this 指针,以便访问_scale成员。


调用 Lambda 表达式

你可以立即调用 lambda 表达式,如下面的代码片段所示。 第二个代码片段演示如何将 lambda 作为参数传递给标准模板库 (STL) 算法,例如 find_if

Dd293599.collapse_all(zh-cn,VS.120).gif示例 1

以下示例声明的 lambda 表达式将返回两个整数的总和并使用参数54立即调用该表达式:

Dd293599.collapse_all(zh-cn,VS.120).gif代码

// calling_lambda_expressions1.cpp
// compile with: /EHsc
#include <iostream>

int main()
{
   using namespace std;
   int n = [] (int x, int y) { return x + y; }(5, 4);
   cout << n << endl;
}

Dd293599.collapse_all(zh-cn,VS.120).gif输出

9

Dd293599.collapse_all(zh-cn,VS.120).gif示例 2

以下示例将 lambda 表达式作为参数传递给 find_if 函数。 如果 lambda 表达式的参数是偶数,则返回 true

Dd293599.collapse_all(zh-cn,VS.120).gif代码

// calling_lambda_expressions2.cpp
// compile with: /EHsc /W4
#include <list>
#include <algorithm>
#include <iostream>

int main()
{
    using namespace std;

    // Create a list of integers with a few initial elements.
    list<int> numbers;
    numbers.push_back(13);
    numbers.push_back(17);
    numbers.push_back(42);
    numbers.push_back(46);
    numbers.push_back(99);

    // Use the find_if function and a lambda expression to find the 
    // first even number in the list.
    const list<int>::const_iterator result = 
        find_if(numbers.begin(), numbers.end(),[](int n) { return (n % 2) == 0; });

    // Print the result.
    if (result != numbers.end()) {
        cout << "The first even number in the list is " << *result << "." << endl;
    } else {
        cout << "The list contains no even numbers." << endl;
    }
}

Dd293599.collapse_all(zh-cn,VS.120).gif输出

The first even number in the list is 42.
嵌套 Lambda 表达式

Dd293599.collapse_all(zh-cn,VS.120).gif示例

你可以将 lambda 表达式嵌套在另一个中,如下例所示。 内部 lambda 表达式将其参数与 2 相乘并返回结果。 外部 lambda 表达式通过其参数调用内部 lambda 表达式并在结果上加 3。

Dd293599.collapse_all(zh-cn,VS.120).gif代码

// nesting_lambda_expressions.cpp
// compile with: /EHsc /W4
#include <iostream>

int main()
{
    using namespace std;

    // The following lambda expression contains a nested lambda
    // expression.
    int timestwoplusthree = [](int x) { return [](int y) { return y * 2; }(x) + 3; }(5);

    // Print the result.
    cout << timestwoplusthree << endl;
}

Dd293599.collapse_all(zh-cn,VS.120).gif输出

13
在方法中使用 Lambda 表达式

Dd293599.collapse_all(zh-cn,VS.120).gif示例

你可以在方法的主体中使用 lambda 表达式。 lambda 表达式可以访问该封闭方法可访问的任何方法或数据成员。 你可以显式或隐式捕获 this 指针,以提供对封闭类的方法和数据成员的访问路径。

你可以在方法中显式使用 this 指针,如下所示:

void ApplyScale(const vector<int>& v) const
{
   for_each(v.begin(), v.end(), 
      [this](int n) { cout << n * _scale << endl; });
}

你也可以隐式捕获 this 指针:

void ApplyScale(const vector<int>& v) const
{
   for_each(v.begin(), v.end(), 
      [=](int n) { cout << n * _scale << endl; });
}

以下示例显示封装小数位数值的Scale类。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值