声明Lambda表达式
example 1
因为lambda表达式是有类型的,所以可以把它指定给一个auto变量或者函数对象,如下所示:
// 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;
}
Output
5
7
example 2
Visual C++编译器在Lambda表达式声明时绑定他的捕获变量,而不是函数调用时。下面的例子展示,一个lambda表达式按值传递捕获本地变量i,按引用传递捕获本地变量j。由于i是按值传递捕获的,所以在重新指定i的值对表达式的结果没有影响,而引用传递j则相反:
// 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;
}
Output
47
调用lambda表达式
你可以向下面的片断展示的那样,立即调用且个lambda表达式。
第二个片断展示了如何把Lambda作为参数传递给标准模板库(STL)算法,
例如find_if。
Example 1
这个例子声明一个返回值为两人个整型数之和的Lambda表达式,并且使用参数5和4立即调用这个表达式:
// 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;
}
Output
9
Example 2
这个例子传递一个Lambda表达式作为参数查找find_if函数。如果它的参数
是一个偶数,这个Lambda表达式返回true:
// 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;
}
}
Output
The first even number in the list is 42.
备注:
关于find_if函数的更多信息,请动动发财手,戳这里
关于展示的普通算法的STL函数的更多信息,看这里
嵌套Lambda表达式
你可以像展示的例子那样,在一个Lambda表达式中嵌套另一个。里面的表达式将参数乘以2并返回结果,外面的表达式调用内部的表达式,将它的参数加3输出:
// 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;
}
Output
13
备注:
在这个例子中,In this example, [](int y) { return y * 2; }是嵌套Lambda表达式。
高阶Lambda函数
很多程序语言支持高阶函数的概念。一个高阶函数就是一个Lambda表达式将另一个函数表达式作为它的参数或者返回一个Lambda表达式。你可以使用这个函数类使一个C++Lambda表达式来表现得像一个高阶函数。下面的例子展示了一个返回函数对象的Lambda表达式和一个将函数对象作为参数的Lambda表达式:
// higher_order_lambda_expression.cpp
// compile with: /EHsc /W4
#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 addtwointegers = [](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 multiplies by 2.
auto higherorder = [](const function<int(int)>& f, int z) {
return f(z) * 2;
};
// Call the lambda expression that is bound to higherorder.
auto answer = higherorder(addtwointegers(7), 8);
// Print the result, which is (7+8)*2.
cout << answer << endl;
}
Output
30
在函数中使用Lambda表达式
你可以在一个函数体中使用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; });
}
下面的例子展示规模类,它封装了一个规模值。
// function_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);
}
Output
3
6
9
12
备注:
ApplyScale函数使用一个Lambda表达式来打印scale产品的值,和每个在
vector对象的元素。Lambda表达式隐式捕获this确保它能访问_scale成员。
在模板中使用lambda表达式
因为Lambda表达式是有类型的,你可以在C++模板中使用它们。下面的例子显示了negate_all和print_all函数。negate_all函数在vector中的每个元素上使用一元操作符。print_all函数打印每个vector对象中的元素到控制台:
// template_lambda_expression.cpp
// compile with: /EHsc
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
// Negates each element in the vector object. Assumes signed data type.
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 signed integers with a few elements.
vector<int> v;
v.push_back(34);
v.push_back(-43);
v.push_back(56);
print_all(v);
negate_all(v);
cout << "After negate_all():" << endl;
print_all(v);
}
Output
34
-43
56
After negate_all():
-34
43
-56
备注:
更多关于C++模板的信息,请看这里
处理异常
一个lambda表达式的函数体遵循结构化异常处理(SEH)和C ++异常处理的规则。您可以在lambda表达式的函数体处理引发的异常或延迟异常处理在函数闭包范围。下面的例子使用for_each函数和Lambda表达式,用另一个的值来填充vector对象。它采用的try / catch块来处理的第一个向量的非法访问。
// eh_lambda_expression.cpp
// compile with: /EHsc /W4
#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 valid subscript. It will trigger an 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;
};
}
Output
Caught 'invalid vector<T> subscript'.
备注:
关于异常处理的更多信息,请查看Visual C++异常处理
用托管类型使用Lambda表达式(C ++ / CLI)
Lambda表达式的捕获子句不能包含有一个托管类型的变量。但是,您可以传送一个具有托管类型的参数到lambda表达式的参数列表中。 下列的例子包含一个Lambda表达式,它通过值传递捕获本地未托管的变量ch ,使用一个System.String对象作为它的参数。
// 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");
}
Output
Hello!
重要
Lambdas在下列普通语言运行时管理实体中并不被支持:ref class, ref struct, value class, and value struct.