Lambda 運算式的範例
這個主題包含在您的程式碼範例將說明如何使用 Lambda 運算式。 如需 Lambda 運算式的概觀,請參閱 在 C++ 中使用 lambda 運算式。 如需 Lambda 運算式的詳細資訊,請參閱 Lambda 運算式語法。
本章節內容
範例:宣告 Lambda 運算式
範例:呼叫 Lambda 運算式
範例:巢狀 Lambda 運算式
範例:高階 Lambda 函式
範例:使用方法中的一個 Lambda 運算式
範例:使用範本的 Lambda 運算式
範例:處理例外狀況。
範例:使用 Managed 型別的 Lambda 運算式
範例:宣告 Lambda 運算式
描述
因為 Lambda 運算式的型別為,如下列範例所示,您可以將它加入至 auto 變數或物件, function :
程式碼
// 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; };
}
註解
如需 auto 關鍵字的詳細資訊,請參閱 自動關鍵字 (型別推算)。 如需 function class 的詳細資訊,請參閱function Class。
雖然 Lambda 運算式在方法或函式主體通常宣告,您可將它們宣告為任何能初始化變數。
描述
Visual C++ 編譯器繫結將 Lambda 運算式為其擷取的變數,在運算式宣告時,而不是運算式時呼叫。 下列範例會示範以傳值方式擷取區域變數 i 和區域變數 j 由參考的 Lambda 運算式。 因為 Lambda 運算式是由值擷取 i , i 的重新配置行為在程式之後不會影響這個運算式的結果。 不過,,因為 Lambda 運算式是以傳址方式擷取 j , j 的重新配置行為會影響這個運算式的結果。
程式碼
// 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;
}
Output
47
註解
[本章節內容]
範例:呼叫 Lambda 運算式
您可以直接呼叫 Lambda 運算式或將它當做引數傳遞至標準樣板程式庫" (Standard (STL) 演算法 (例如 find_if。
描述
下列範例會宣告兩個整數的加總並立即呼叫運算式使用引數 5 和 4的 Lambda 運算式:
程式碼
// 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
描述
下列範例會將 Lambda 運算式當做引數傳遞至 find_if 函式。 ;如果它的參數是偶數, Lambda 運算式傳回 true 。
程式碼
// 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;
}
}
Output
The first even number in the list is 42.
註解
如需 find_if 函式的詳細資訊,請參閱 find_if。 如需執行 STL 演算法的函式的詳細資訊,請參閱 <algorithm>。
描述
您可以使用函式呼叫運算子,您可以叫用指派給變數的 Lambda 運算式, operator()。 下列範例將 Lambda 運算式指派給 auto 變數並使用函式呼叫運算子叫用 Lambda 運算式:
程式碼
// 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;
}
Output
33
註解
如需函式呼叫運算子的詳細資訊,請參閱 函式呼叫 (C++)。
[本章節內容]
範例:巢狀 Lambda 運算式
描述
您可以巢狀方式置於另一個主版頁面中將 Lambda 運算式。 下列範例顯示包含另一個 Lambda 運算式的 Lambda 運算式。 內部 Lambda 運算式由其引數為 2 並傳回結果。 外部 Lambda 運算式會以其引數的內部 Lambda 運算式並將 3 加入至結果。
程式碼
// 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;
}
Output
13
註解
在此範例中, [](int y) { return y * 2; } 是巢狀 Lambda 運算式。
[本章節內容]
範例:高階 Lambda 函式
描述
許多程式設計語言都支援一種 高階函式的概念。一個高階函式是使用另一個 Lambda 運算式做為其引數或傳回 Lambda 運算式的 Lambda 運算式。 您可以使用 function 類別允許 . C ++ Lambda 運算式的行為就像是高階函式。 下列範例示範傳回 function 物件和 Lambda 運算式使用 function 物件做為其引數的 Lambda 運算式:
程式碼
// 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;
}
Output
16
註解
[本章節內容]
範例:使用方法中的一個 Lambda 運算式
描述
您可以在方法的主體中使用 Lambda 運算式。 Lambda 運算式可以存取封入方法可存取的方法或資料成員。 您可以明確或隱含地擷取 this 指標提供對封入類別的方法和資料成員。
下列範例顯示 Scale 類別,封裝的縮放值。 ApplyScale 方法使用 Lambda 運算式列印每個項目 Product] 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);
}
Output
9
18
27
註解
如下列範例所示,您可以在方法中就可以明確使用 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; });
}
[本章節內容]
範例:使用範本的 Lambda 運算式
描述
因為 Lambda 運算式的型別為,您可以搭配 C++ 樣板。 下列範例顯示 negate_all 和 print_all 函式。 negate_all 函式套用一元 operator- 至 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.
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);
}
Output
-34
43
-56
註解
如需 C++ 樣板的詳細資訊,請參閱 範本。
[本章節內容]
範例:處理例外狀況。
描述
Lambda 運算式的主體遵循兩個規則結構化例外狀況處理 (SEH) 和 C++ 例外狀況處理。 您可以在 Lambda 運算式的主體中引發的例外狀況或延後例外處理至封閉範圍中。 下列範例會使用 for_each 函式和一個 Lambda 運算式以另一個的值填滿 vector 物件。 它會使用 try/catch 區塊處理至第一個向量的無效的存取。
程式碼
// 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;
};
}
Output
Caught 'invalid vector<T> subscript'.
註解
如需例外狀況處理的詳細資訊,請參閱在 Visual C++ 中處理的例外狀況。
[本章節內容]
範例:使用 Managed 型別的 Lambda 運算式
描述
Lambda 運算式的擷取子句不能包含 Managed 型別的變數。 不過,您也可以使用 Managed 型別的引數到 Lambda 運算式參數清單。 下列範例包含由值擷取本機 Unmanaged 變數 ch 並採取 System.String 物件做為其參數的 Lambda 運算式:
程式碼
// 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!
註解
您也可以使用 STL/CLR 程式庫的 Lambda 運算式。 如需 STL/CLR 的詳細資訊,請參閱 STL/CLR 程式庫參考。
[本章節內容]