實例講授C++編程中lambda表達式的應用。本站提示廣大學習愛好者:(實例講授C++編程中lambda表達式的應用)文章只能為提供參考,不一定能成為您想要的結果。以下是實例講授C++編程中lambda表達式的應用正文
函數對象與Lambdas
你編寫代碼時,特別是應用 STL 算法時,能夠會應用函數指針和函數對象來處理成績和履行盤算。函數指針和函數對象各有益弊。例如,函數指針具有最低的語法開支,但不堅持規模內的狀況,函數對象可堅持狀況,但須要類界說的語法開支。
lambda 聯合了函數指針和函數對象的長處並防止其缺陷。lambda 與函數對象類似的是靈巧而且可以堅持狀況,但分歧的是其簡練的語法不須要顯式類界說。 應用lambda,比擬等效的函數對象代碼,您可以寫出不太龐雜而且不輕易失足的代碼。
上面的示例比擬lambda和函數對象的應用。 第一個示例應用 lambda 向掌握台打印 vector 對象中的每一個元素是偶數照樣奇數。第二個示例應用函數對象來完成雷同義務。
示例 1:應用 lambda
此示例將一個 lambda 傳遞給 for_each 函數。該 lambda 打印一個成果,該成果指出 vector 對象中的每一個元素是偶數照樣奇數。
代碼
// even_lambda.cpp
// compile with: cl /EHsc /nologo /W4 /MTd
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Create a vector object that contains 10 elements.
vector<int> v;
for (int i = 1; i < 10; ++i) {
v.push_back(i);
}
// Count the number of even numbers in the vector by
// using the for_each function and a lambda.
int evenCount = 0;
for_each(v.begin(), v.end(), [&evenCount] (int n) {
cout << n;
if (n % 2 == 0) {
cout << "is even" << endl;
++evenCount;
} else {
cout << "is odd" << endl;
}
});
// Print the count of even numbers to the console.
cout << "There are " << evenCount
<< " even numbers in the vector." << endl;
}
輸入
1 is even 2 is odd 3 is even 4 is odd 5 is even 6 is odd 7 is even 8 is odd 9 is even There are 4 even numbers in the vector.
批注
在此示例中,for_each 函數的第三個參數是一個lambda。 [&evenCount] 部門指定表達式的捕捉子句,(int n) 指定參數列表,殘剩部門指定表達式的主體。
示例 2:應用函數對象
有時 lambda 過於宏大,沒法在上一示例的基本上年夜幅度擴大。下一示例應用函數對象(而非 lambda)和 for_each 函數,以發生與示例 1 雷同的成果。兩個示例都在 vector 對象中存儲偶數的個數。為堅持運算的狀況,FunctorClass 類經由過程援用存儲 m_evenCount 變量作為成員變量。為履行該運算,FunctorClass 完成函數挪用運算符 operator()。Visual C++ 編譯器生成的代碼與示例 1 中的 lambda 代碼在年夜小和機能上相差無幾。關於相似本文中示例的根本成績,較為簡略的 lambda 設計能夠優於函數對象設計。然則,假如你以為該功效在未來能夠須要嚴重擴大,則應用函數對象設計,如許代碼保護會更簡略。
有關 operator() 的具體信息,請參閱函數挪用 (C++)。
代碼
// even_functor.cpp
// compile with: /EHsc
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
class FunctorClass
{
public:
// The required constructor for this example.
explicit FunctorClass(int& evenCount)
: m_evenCount(evenCount) { }
// The function-call operator prints whether the number is
// even or odd. If the number is even, this method updates
// the counter.
void operator()(int n) const {
cout << n;
if (n % 2 == 0) {
cout << " is even " << endl;
++m_evenCount;
} else {
cout << " is odd " << endl;
}
}
private:
// Default assignment operator to silence warning C4512.
FunctorClass& operator=(const FunctorClass&);
int& m_evenCount; // the number of even variables in the vector.
};
int main()
{
// Create a vector object that contains 10 elements.
vector<int> v;
for (int i = 1; i < 10; ++i) {
v.push_back(i);
}
// Count the number of even numbers in the vector by
// using the for_each function and a function object.
int evenCount = 0;
for_each(v.begin(), v.end(), FunctorClass(evenCount));
// Print the count of even numbers to the console.
cout << "There are " << evenCount
<< " even numbers in the vector." << endl;
}
輸入
1 is even 2 is odd 3 is even 4 is odd 5 is even 6 is odd 7 is even 8 is odd 9 is even There are 4 even numbers in the vector.
聲明 Lambda 表達式
示例 1
因為 lambda 表達式已類型化,所以你可以將其指派給 auto 變量或 function 對象,以下所示:
代碼
// 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;
}
輸入
5 7
備注
固然 lambda 表達式多在函數的主體中聲明,然則可以在初始化變量的任何處所聲明。
示例 2
Visual C++ 編譯器將在聲明而非挪用 lambda 表達式時,將表達式綁定到捕捉的變量。以下示例顯示一個經由過程值捕捉部分變量 i 並經由過程援用捕捉部分變量 j 的 lambda 表達式。因為 lambda 表達式經由過程值捕捉 i,是以在法式前面部門中從新指派 i 不影響該表達式的成果。然則,因為 lambda 表達式經由過程援用捕捉 j,是以從新指派 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;
}
輸入
47
挪用 Lambda 表達式
你可以立刻挪用 lambda 表達式,以下面的代碼片斷所示。第二個代碼片斷演示若何將 lambda 作為參數傳遞給尺度模板庫 (STL) 算法,例如 find_if。
示例 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;
}
輸入
9
示例 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;
}
}
輸入
The first even number in the list is 42.
嵌套 Lambda 表達式
示例
你可以將 lambda 表達式嵌套在另外一個中,以下例所示。外部 lambda 表達式將其參數與 2 相乘並前往成果。內部 lambda 表達式經由過程其參數挪用外部 lambda 表達式並在成果上加 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;
}
輸入
13
備注
// 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;
}
輸入
30
在函數中應用 Lambda 表達式
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 類。
// 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);
}
輸入
3 6 9 12
備注
ApplyScale 函數應用 lambda 表達式打印小數位數值與 vector 對象中的每一個元素的乘積。lambda 表達式隱式捕捉 this 指針,以便拜訪 _scale 成員。
合營應用 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. 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);
}
輸入
34 -43 56 After negate_all(): -34 43 -56
處置異常
示例
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;
};
}
輸入
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");
}
輸入
Hello!