C++ AMP: Lambda表达式的示例

本主题在程序中包含演示如何使用 lambda 表达式的示例。 有关 lambda 表达式的概述,请参见 在C++中Lambda表达式 有关 lambda 表达式结构的更多信息,请参见 Lambda表达式语法

Dd293599.collapse_all(zh-cn,VS.110).gif描述

由于键入 lambda 表达式,因此可以将其分配给auto变量或分配到 function对象,如以下示例所示:

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

// declaring_lambda_expressions1.cpp
#include <functional>

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

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

Dd293599.collapse_all(zh-cn,VS.110).gif注释

有关 auto 关键字的更多信息,请参见 auto关键字(类型推导) 有关 function class 的更多信息,请参见function Class

尽管 lambda 表达式多在方法或函数体中声明,但是也可以在初始化变量的任何地方声明。

Dd293599.collapse_all(zh-cn,VS.110).gif描述

Visual C++ 编译器将一个 lambda 表达式绑定到其捕获的变量上(在声明该表达式而不是调用该表达式时)。 以下示例显示 lambda 表达式,通过值捕获本地变量的 i,并通过引用捕获本地变量的 j 因为 lambda 表达式通过值捕获 i ,因此 在该程序后面内容中的 i 的重新分配不影响该表达式的结果。 但是,因为 lambda 表达式用引用捕获 jj 的重新分配确实影响该表达式的结果。

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

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

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.110).gifOutput

47

Dd293599.collapse_all(zh-cn,VS.110).gif注释

可以直接调用 lambda 表达式或将其作为参数传递给标准模板库 (STL) 算法,例如 find_if

Dd293599.collapse_all(zh-cn,VS.110).gif描述

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

Dd293599.collapse_all(zh-cn,VS.110).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.110).gifOutput

9

Dd293599.collapse_all(zh-cn,VS.110).gif描述

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

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

// calling_lambda_expressions2.cpp
// compile with: /EHsc
#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.110).gifOutput

The first even number in the list is 42.

Dd293599.collapse_all(zh-cn,VS.110).gif注释

有关 find_if 函数的更多信息,请参见 find_if 有关进行计算 STL 函数的更多信息,请参见 <algorithm>

Dd293599.collapse_all(zh-cn,VS.110).gif描述

使用函数调用运算符 operator(),可以调用分配到变量的 lambda 表达式。 以下示例将 lambda 表达式赋给 auto 变量,然后使用函数调用运算符调用 lambda 表达式:

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

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

int main()
{
   using namespace std;

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

   // Invoke the function object and print its result.
   cout << f(21, 12) << endl;
}

Dd293599.collapse_all(zh-cn,VS.110).gifOutput

33

Dd293599.collapse_all(zh-cn,VS.110).gif注释

有关此函数调用运算符的更多信息,请参见 函数调用(C++)

[本节内容]

Dd293599.collapse_all(zh-cn,VS.110).gif描述

可以将一个 lambda 表达式嵌套到另一个中。 以下示例显示包含另一个 lambda 表达式的 lambda 表达式。 内部 lambda 表达式将其参数与 2 相乘并返回结果。 外部 lambda 表达式调用其参数的内部 lambda 表达式并将 3 添加到结果。

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

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

int main()
{
   using namespace std;

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

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

Dd293599.collapse_all(zh-cn,VS.110).gifOutput

13

Dd293599.collapse_all(zh-cn,VS.110).gif注释

在此示例中, [](int y) { return y * 2; } 是嵌套 lambda 表达式。

[本节内容]

Dd293599.collapse_all(zh-cn,VS.110).gif描述

许多编程语言支持一个高阶函数的概念。一个高阶函数是采用另一个 lambda 表达式作为其参数或返回 lambda 表达式的 lambda 表达式。 可以使用 function 类,以允许 C++ lambda 表达式的行为与高阶函数的行为一样。 以下示例显示返回 function 对象和采用 function 对象作为其参数的 lambda 表达式的 lambda 表达式:

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

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

int main()
{
   using namespace std;

   // The following code declares a lambda expression that returns 
   // another lambda expression that adds two numbers. 
   // The returned lambda expression captures parameter x by value.
   auto g = [](int x) -> function<int (int)> 
      { return [=](int y) { return x + y; }; };

   // The following code declares a lambda expression that takes another
   // lambda expression as its argument.
   // The lambda expression applies the argument z to the function f
   // and adds 1.
   auto h = [](const function<int (int)>& f, int z) 
      { return f(z) + 1; };

   // Call the lambda expression that is bound to h. 
   auto a = h(g(7), 8);

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

Dd293599.collapse_all(zh-cn,VS.110).gifOutput

16

Dd293599.collapse_all(zh-cn,VS.110).gif注释

Dd293599.collapse_all(zh-cn,VS.110).gif描述

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

以下示例显示了封装范围值的 Scale 类。 ApplyScale 方法使用 lambda 表达式按产品 vector 对象和缩放打印每个元素。 lambda 表达式显式捕获 this 指针,以便其可以访问 _scale 成员。

// method_lambda_expression.cpp
// compile with: /EHsc
#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(), 
         [this](int n) { cout << n * _scale << endl; });
   }

private:
   int _scale;
};

int main()
{
   vector<int> values;
   values.push_back(3);
   values.push_back(6);
   values.push_back(9);

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

Dd293599.collapse_all(zh-cn,VS.110).gifOutput

9
18
27

Dd293599.collapse_all(zh-cn,VS.110).gif注释

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

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

也可以捕获 this 指针显示性,如以下示例所示:

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

[本节内容]

Dd293599.collapse_all(zh-cn,VS.110).gif描述

由于键入 lambda 表达式,因此您可以将它们与 C++ 模板一起使用。 下面的示例显示 negate_allprint_all 函数。 negate_all 函数把一元 operator- 应用到 vector 对象中的每个元素上。 print_all 函数打印 vector 对象中的每个元素到控制台。

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

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

using namespace std;

// Negates each element in the vector object.
template <typename T> 
void negate_all(vector<T>& v)
{
    for_each(v.begin(), v.end(), [] (T& n) { n = -n; } );
}

// Prints to the console each element in the vector object.
template <typename T> 
void print_all(const vector<T>& v)
{
   for_each(v.begin(), v.end(), [] (const T& n) { cout << n << endl; } );
}

int main()
{
   // Create a vector of integers with a few initial elements.
   vector<int> v;
   v.push_back(34);
   v.push_back(-43);
   v.push_back(56);

   // Negate each element in the vector.
   negate_all(v);

   // Print each element in the vector.
   print_all(v);
}

Dd293599.collapse_all(zh-cn,VS.110).gifOutput

-34
43
-56

Dd293599.collapse_all(zh-cn,VS.110).gif注释

有关 C++ 模板的更多信息,请参见 模板

[本节内容]

Dd293599.collapse_all(zh-cn,VS.110).gif描述

lambda 表达式的主体遵循两个规则结构化异常处理 (SEH) 和 C++ 异常处理。 可以在 lambda 表达式主体中处理引发的异常或将异常处理延迟至封闭作用域。 以下示例使用 for_each 函数和 lambda 表达式使用另一个值填充一个 vector 对象。 使用一个 try/catch 块处理到第一个矢量的无效访问。

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

// eh_lambda_expression.cpp
// compile with: /EHsc
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

int main()
{
   // Create a vector that contains 3 elements.
   vector<int> elements(3);

   // Create another vector that contains index values.
   vector<int> indices(3);
   indices[0] = 0;
   indices[1] = -1; // This is not a subscript. It will trigger the exception.
   indices[2] = 2;

   // Use the values from the vector of index values to 
   // fill the elements vector. This example uses a 
   // try/catch block to handle invalid access to the 
   // elements vector.
   try
   {
       for_each(indices.begin(), indices.end(), 
           [&] (int index) { elements.at(index) = index; });
   }
   catch (const out_of_range& e) 
   {
       cerr << "Caught '" << e.what() << "'." << endl;
   };
}

Dd293599.collapse_all(zh-cn,VS.110).gifOutput

Caught 'invalid vector<T> subscript'.

Dd293599.collapse_all(zh-cn,VS.110).gif注释

有关异常处理的更多信息,请参见异常处理在Visual C++

[本节内容]

Dd293599.collapse_all(zh-cn,VS.110).gif描述

lambda 表达式中获取子句不能包含具有托管类型的变量。 但是,您可以传递托管类型参数到 lambda 表达式参数列表。 以下示例包含 lambda 表达式,通过值捕获本地非托管变量 ch,并采用 System.String 对象作为其参数:

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

// managed_lambda_expression.cpp
// compile with: /clr
using namespace System;

int main()
{
    char ch = '!'; // a local unmanaged variable
    
    // The following lambda expression captures local variables
    // by value and takes a managed String object as its parameter.
    [=] (String ^s) 
        { Console::WriteLine(s + Convert::ToChar(ch)); }("Hello");
}

Dd293599.collapse_all(zh-cn,VS.110).gifOutput

Hello!

Dd293599.collapse_all(zh-cn,VS.110).gif注释

还可以使用具有 STL/CLR 库的 lambda 表达式。 有关 STL/CLR 的更多信息,请参见 STL/CLR 库参考

[本节内容]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值