亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb

首頁 > 編程 > C++ > 正文

實例講解C++編程中lambda表達式的使用

2020-01-26 14:44:39
字體:
來源:轉載
供稿:網友

函數對象與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 even2 is odd3 is even4 is odd5 is even6 is odd7 is even8 is odd9 is evenThere 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 even2 is odd3 is even4 is odd5 is even6 is odd7 is even8 is odd9 is evenThere 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;}

輸出

57

備注
雖然 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

備注
在該示例中,[](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 /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 表達式
示例
你可以在函數的主體中使用 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 類。

// 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);}

輸出

36912

備注
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-4356After negate_all():-3443-56

處理異常
示例
lambda 表達式的主體遵循結構化異常處理 (SEH) 和 C++ 異常處理的原則。你可以在 lambda 表達式主體中處理引發的異?;驅惓L幚硗七t至封閉范圍。以下示例使用 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: /clrusing 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!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb
伊人伊成久久人综合网小说| 91chinesevideo永久地址| 国产亚洲精品久久久久久牛牛| 欧美成年人视频| 最新91在线视频| 欧美激情精品久久久久久久变态| 亚洲精品久久久一区二区三区| 97色伦亚洲国产| 性色av一区二区三区在线观看| 国产精品欧美日韩| 日韩男女性生活视频| 国内精品一区二区三区四区| 欧美在线日韩在线| 91中文精品字幕在线视频| 性欧美xxxx视频在线观看| 成人xvideos免费视频| 欧美成人激情视频| 欧美限制级电影在线观看| 91精品国产自产91精品| 亚洲www在线观看| 成人免费在线网址| 亚洲va男人天堂| 亚洲女在线观看| 欧美中文在线观看| 激情成人中文字幕| 久久黄色av网站| 毛片精品免费在线观看| 亚洲人成电影网站色xx| 精品人伦一区二区三区蜜桃网站| 在线亚洲午夜片av大片| 久久免费成人精品视频| 国产精品九九久久久久久久| 成人精品aaaa网站| 国外日韩电影在线观看| 久久精品久久久久电影| 欧美中文在线字幕| 91精品视频在线播放| 欧美成人自拍视频| 亚洲一区二区三区乱码aⅴ蜜桃女| 日韩在线欧美在线| 日韩欧美中文免费| 日韩欧美在线免费| 亚洲国产成人av在线| 国产精国产精品| 欧美日韩中文在线观看| 亚洲乱码一区二区| 色偷偷91综合久久噜噜| 国产欧美日韩专区发布| 久久6免费高清热精品| 九九久久久久久久久激情| 18久久久久久| 欧美激情性做爰免费视频| 久久成人免费视频| 日韩成人高清在线| 日韩精品中文字| 久久久久久国产精品三级玉女聊斋| 在线看日韩欧美| 欧美日韩一二三四五区| 日韩av最新在线| 精品亚洲一区二区三区在线播放| 亚洲二区在线播放视频| 91精品久久久久| 97色在线视频| 国产精品入口夜色视频大尺度| 91日本视频在线| 97超碰蝌蚪网人人做人人爽| 亚洲欧美日本伦理| 欧美精品18videos性欧| 国产专区精品视频| 97在线免费视频| 欧美黑人巨大xxx极品| 欧洲成人午夜免费大片| 97精品国产91久久久久久| 亚洲性视频网址| 欧美一级免费看| 国产精品电影网| 国产一区二区三区在线视频| 亚洲日本aⅴ片在线观看香蕉| 国产成人亚洲综合91| 永久免费看mv网站入口亚洲| 久久久噜久噜久久综合| 国产精品高清网站| 欧美一区二区三区精品电影| 欧美大尺度激情区在线播放| 欧美精品一二区| 狠狠躁夜夜躁人人爽天天天天97| 美女久久久久久久久久久| 最近2019年手机中文字幕| 亚洲第一页在线| 韩国三级日本三级少妇99| 日韩男女性生活视频| 欧美性猛交xxxx| xxav国产精品美女主播| 欧美日韩国产成人高清视频| 欧美激情久久久| 亚洲成人激情图| 亚洲欧美激情四射在线日| 亚洲a级在线观看| 91美女片黄在线观看游戏| 久久久久久久成人| xvideos成人免费中文版| 久久99国产精品自在自在app| 久色乳综合思思在线视频| 社区色欧美激情 | 国产福利视频一区二区| 欧美三级欧美成人高清www| 成人黄色生活片| 国产精品观看在线亚洲人成网| 主播福利视频一区| 亚洲伊人久久综合| 亚洲精品自拍第一页| 久久国产一区二区三区| 91久久精品美女| 亚洲精品国产品国语在线| 在线观看欧美成人| 一区二区三区回区在观看免费视频| 九九九热精品免费视频观看网站| 亚洲一区二区三区sesese| 欧美国产欧美亚洲国产日韩mv天天看完整| 成人www视频在线观看| 亚洲综合中文字幕在线观看| 日韩精品www| 精品无人区太爽高潮在线播放| 97超级碰碰人国产在线观看| 亚洲在线观看视频网站| 成人在线小视频| 国产亚洲欧美日韩一区二区| 精品久久久久久久久久国产| 日韩在线观看免费全| 高跟丝袜一区二区三区| 国产精品免费观看在线| 成人福利网站在线观看11| 午夜精品国产精品大乳美女| 欧美日韩在线免费| 亚洲肉体裸体xxxx137| 久久中国妇女中文字幕| 欧美黄色片免费观看| 国产日韩欧美影视| 国产亚洲欧美aaaa| 中文字幕欧美精品在线| 欧美电影免费观看高清| 国产一区二区三区四区福利| 欧美在线视频免费播放| 日本欧美中文字幕| 超在线视频97| 在线精品91av| 欧美在线性视频| 亚洲精品久久久久中文字幕二区| 亚洲人成欧美中文字幕| 成人黄色免费网站在线观看| 国产69久久精品成人看| 亚洲精品日韩欧美| 国产成人一区二区三区小说| 欧美黑人一级爽快片淫片高清| 日韩精品999| 久久精品影视伊人网| 亚洲精品午夜精品| 亚洲天堂一区二区三区| 免费不卡欧美自拍视频| 亚洲xxx大片| 国产视频久久久久| 日韩av在线一区二区| 国产日韩欧美自拍| 亚洲日本中文字幕|