最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

實(shí)例講解C++編程中l(wèi)ambda表達(dá)式的使用

 更新時(shí)間:2016年01月25日 15:07:16   投稿:goldensun  
這篇文章主要介紹了C++編程中l(wèi)ambda表達(dá)式的使用實(shí)例,lambda表達(dá)式特性的引入在C++11中可謂千呼萬喚始出來,非常重要,需要的朋友可以參考下

函數(shù)對象與Lambdas
你編寫代碼時(shí),尤其是使用 STL 算法時(shí),可能會(huì)使用函數(shù)指針和函數(shù)對象來解決問題和執(zhí)行計(jì)算。函數(shù)指針和函數(shù)對象各有利弊。例如,函數(shù)指針具有最低的語法開銷,但不保持范圍內(nèi)的狀態(tài),函數(shù)對象可保持狀態(tài),但需要類定義的語法開銷。
lambda 結(jié)合了函數(shù)指針和函數(shù)對象的優(yōu)點(diǎn)并避免其缺點(diǎn)。lambda 與函數(shù)對象相似的是靈活并且可以保持狀態(tài),但不同的是其簡潔的語法不需要顯式類定義。 使用lambda,相比等效的函數(shù)對象代碼,您可以寫出不太復(fù)雜并且不容易出錯(cuò)的代碼。
下面的示例比較lambda和函數(shù)對象的使用。 第一個(gè)示例使用 lambda 向控制臺(tái)打印 vector 對象中的每個(gè)元素是偶數(shù)還是奇數(shù)。第二個(gè)示例使用函數(shù)對象來完成相同任務(wù)。
示例 1:使用 lambda
此示例將一個(gè) lambda 傳遞給 for_each 函數(shù)。該 lambda 打印一個(gè)結(jié)果,該結(jié)果指出 vector 對象中的每個(gè)元素是偶數(shù)還是奇數(shù)。
代碼

// 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 函數(shù)的第三個(gè)參數(shù)是一個(gè)lambda。 [&evenCount] 部分指定表達(dá)式的捕獲子句,(int n) 指定參數(shù)列表,剩余部分指定表達(dá)式的主體。
示例 2:使用函數(shù)對象
有時(shí) lambda 過于龐大,無法在上一示例的基礎(chǔ)上大幅度擴(kuò)展。下一示例使用函數(shù)對象(而非 lambda)以及 for_each 函數(shù),以產(chǎn)生與示例 1 相同的結(jié)果。兩個(gè)示例都在 vector 對象中存儲(chǔ)偶數(shù)的個(gè)數(shù)。為保持運(yùn)算的狀態(tài),F(xiàn)unctorClass 類通過引用存儲(chǔ) m_evenCount 變量作為成員變量。為執(zhí)行該運(yùn)算,F(xiàn)unctorClass 實(shí)現(xiàn)函數(shù)調(diào)用運(yùn)算符 operator()。Visual C++ 編譯器生成的代碼與示例 1 中的 lambda 代碼在大小和性能上相差無幾。對于類似本文中示例的基本問題,較為簡單的 lambda 設(shè)計(jì)可能優(yōu)于函數(shù)對象設(shè)計(jì)。但是,如果你認(rèn)為該功能在將來可能需要重大擴(kuò)展,則使用函數(shù)對象設(shè)計(jì),這樣代碼維護(hù)會(huì)更簡單。
有關(guān) operator() 的詳細(xì)信息,請參閱函數(shù)調(diào)用 (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 表達(dá)式
示例 1
由于 lambda 表達(dá)式已類型化,所以你可以將其指派給 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 表達(dá)式多在函數(shù)的主體中聲明,但是可以在初始化變量的任何地方聲明。
示例 2
Visual C++ 編譯器將在聲明而非調(diào)用 lambda 表達(dá)式時(shí),將表達(dá)式綁定到捕獲的變量。以下示例顯示一個(gè)通過值捕獲局部變量 i 并通過引用捕獲局部變量 j 的 lambda 表達(dá)式。由于 lambda 表達(dá)式通過值捕獲 i,因此在程序后面部分中重新指派 i 不影響該表達(dá)式的結(jié)果。但是,由于 lambda 表達(dá)式通過引用捕獲 j,因此重新指派 j 會(huì)影響該表達(dá)式的結(jié)果。
代碼

// 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

調(diào)用 Lambda 表達(dá)式
你可以立即調(diào)用 lambda 表達(dá)式,如下面的代碼片段所示。第二個(gè)代碼片段演示如何將 lambda 作為參數(shù)傳遞給標(biāo)準(zhǔn)模板庫 (STL) 算法,例如 find_if。
示例 1
以下示例聲明的 lambda 表達(dá)式將返回兩個(gè)整數(shù)的總和并使用參數(shù) 5 和 4 立即調(diào)用該表達(dá)式:
代碼

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

輸出

復(fù)制代碼 代碼如下:
9

示例 2
以下示例將 lambda 表達(dá)式作為參數(shù)傳遞給 find_if 函數(shù)。如果 lambda 表達(dá)式的參數(shù)是偶數(shù),則返回 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 表達(dá)式
示例
你可以將 lambda 表達(dá)式嵌套在另一個(gè)中,如下例所示。內(nèi)部 lambda 表達(dá)式將其參數(shù)與 2 相乘并返回結(jié)果。外部 lambda 表達(dá)式通過其參數(shù)調(diào)用內(nèi)部 lambda 表達(dá)式并在結(jié)果上加 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;
}

輸出

復(fù)制代碼 代碼如下:
13

備注
在該示例中,[](int y) { return y * 2; } 是嵌套的 lambda 表達(dá)式。
高階 Lambda 函數(shù)
示例
許多編程語言都支持高階函數(shù)的概念。 高階函數(shù)是采用另一個(gè) lambda 表達(dá)式作為其參數(shù)或返回 lambda 表達(dá)式的 lambda 表達(dá)式。你可以使用 function 類,使得 C++ lambda 表達(dá)式具有類似高階函數(shù)的行為。以下示例顯示返回 function 對象的 lambda 表達(dá)式和采用 function 對象作為其參數(shù)的 lambda 表達(dá)式。
代碼
// 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;
}

輸出

復(fù)制代碼 代碼如下:
30

在函數(shù)中使用 Lambda 表達(dá)式
示例
你可以在函數(shù)的主體中使用 lambda 表達(dá)式。lambda 表達(dá)式可以訪問該封閉函數(shù)可訪問的任何函數(shù)或數(shù)據(jù)成員。你可以顯式或隱式捕獲 this 指針,以提供對封閉類的函數(shù)和數(shù)據(jù)成員的訪問路徑。
你可以在函數(shù)中顯式使用 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; });
}

以下示例顯示封裝小數(shù)位數(shù)值的 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 函數(shù)使用 lambda 表達(dá)式打印小數(shù)位數(shù)值與 vector 對象中的每個(gè)元素的乘積。lambda 表達(dá)式隱式捕獲 this 指針,以便訪問 _scale 成員。


配合使用 Lambda 表達(dá)式和模板
示例
由于 lambda 表達(dá)式已類型化,因此你可以將其與 C++ 模板一起使用。下面的示例顯示 negate_all 和 print_all 函數(shù)。 negate_all 函數(shù)將一元 operator- 應(yīng)用于 vector 對象中的每個(gè)元素。 print_all 函數(shù)將 vector 對象中的每個(gè)元素打印到控制臺(tái)。
代碼

// 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 表達(dá)式的主體遵循結(jié)構(gòu)化異常處理 (SEH) 和 C++ 異常處理的原則。你可以在 lambda 表達(dá)式主體中處理引發(fā)的異?;?qū)惓L幚硗七t至封閉范圍。以下示例使用 for_each 函數(shù)和 lambda 表達(dá)式將一個(gè) vector 對象的值填充到另一個(gè)中。它使用 try/catch 塊處理對第一個(gè)矢量的無效訪問。
代碼

// 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'.

備注
有關(guān)異常處理的詳細(xì)信息,請參閱 Visual C++ 中的異常處理。

配合使用 Lambda 表達(dá)式和托管類型 (C++/CLI)
示例
lambda 表達(dá)式的捕獲子句不能包含具有托管類型的變量。但是,你可以將具有托管類型的實(shí)際參數(shù)傳遞到 lambda 表達(dá)式的形式參數(shù)列表。以下示例包含一個(gè) lambda 表達(dá)式,它通過值捕獲局部非托管變量 ch,并采用 System.String 對象作為其參數(shù)。
代碼

// 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!

相關(guān)文章

  • C++最短路徑Dijkstra算法的分析與具體實(shí)現(xiàn)詳解

    C++最短路徑Dijkstra算法的分析與具體實(shí)現(xiàn)詳解

    經(jīng)典的求解最短路徑算法有這么幾種:廣度優(yōu)先算法、Dijkstra算法、Floyd算法。本文是對?Dijkstra算法的總結(jié),該算法適用于帶權(quán)有向圖,可求出起始頂點(diǎn)到其他任意頂點(diǎn)的最小代價(jià)以及對應(yīng)路徑,希望對大家有所幫助
    2023-03-03
  • 一文弄懂C語言如何實(shí)現(xiàn)單鏈表

    一文弄懂C語言如何實(shí)現(xiàn)單鏈表

    單鏈表是由多個(gè)結(jié)點(diǎn)鏈接組成,它的每個(gè)結(jié)點(diǎn)包含兩個(gè)域,一個(gè)數(shù)據(jù)域和一個(gè)鏈接域(地址域),下面這篇文章主要給大家介紹了關(guān)于C語言如何實(shí)現(xiàn)單鏈表的相關(guān)資料,需要的朋友可以參考下
    2021-09-09
  • C++對Json數(shù)據(jù)的友好處理實(shí)現(xiàn)過程

    C++對Json數(shù)據(jù)的友好處理實(shí)現(xiàn)過程

    在Ajax的應(yīng)用中,前臺(tái)基本上會(huì)用到JSON作為數(shù)據(jù)交換格式,所以下面這篇文章主要給大家介紹了關(guān)于C++對Json數(shù)據(jù)的友好處理,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-02-02
  • C語言數(shù)據(jù)結(jié)構(gòu)創(chuàng)建及遍歷十字鏈表

    C語言數(shù)據(jù)結(jié)構(gòu)創(chuàng)建及遍歷十字鏈表

    這篇文章主要介紹了C語言數(shù)據(jù)結(jié)構(gòu)十字鏈表的創(chuàng)建及遍歷,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪
    2021-10-10
  • C語言值傳遞和地址傳遞詳解

    C語言值傳遞和地址傳遞詳解

    大家好,本篇文章主要講的是C語言值傳遞和地址傳遞詳解,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽
    2022-01-01
  • C語言實(shí)現(xiàn)單詞小助手改進(jìn)版

    C語言實(shí)現(xiàn)單詞小助手改進(jìn)版

    這篇文章主要為大家詳細(xì)介紹了C語言實(shí)現(xiàn)單詞小助手的改進(jìn)版,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-10-10
  • 查找算法之二分查找的C++實(shí)現(xiàn)

    查找算法之二分查找的C++實(shí)現(xiàn)

    今天小編就為大家分享一篇關(guān)于查找算法之二分查找的C++實(shí)現(xiàn),小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2018-12-12
  • qt首次連接MYSQL驅(qū)動(dòng)的各種問題圖文詳解

    qt首次連接MYSQL驅(qū)動(dòng)的各種問題圖文詳解

    通常來說,我們對數(shù)據(jù)庫的操作更多地在于對數(shù)據(jù)庫表的操作,下面這篇文章主要給大家介紹了關(guān)于qt首次連接MYSQL驅(qū)動(dòng)的各種問題,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-04-04
  • 線程池的原理與實(shí)現(xiàn)詳解

    線程池的原理與實(shí)現(xiàn)詳解

    下面利用C語言來實(shí)現(xiàn)一個(gè)簡單的線程池,為了使得這個(gè)線程池庫使用起來更加方便,特在C實(shí)現(xiàn)中加入了一些OO的思想,與Objective-C不同,它僅僅是使用了struct來模擬了c++中的類,其實(shí)這種方式在linux內(nèi)核中大量可見
    2013-09-09
  • 利用C++求絕對值的幾種方法例子

    利用C++求絕對值的幾種方法例子

    相信大家在學(xué)習(xí)C++時(shí),應(yīng)該都有做過求絕對值的題目,下面這篇文章主要給大家介紹了關(guān)于利用C++求絕對值的幾種方法例子,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-04-04

最新評論

库伦旗| 水城县| 察隅县| 大关县| 嘉鱼县| 察雅县| 桓台县| 济阳县| 察隅县| 清新县| 抚宁县| 曲沃县| 连南| 偃师市| 望谟县| 德保县| 吴江市| 罗江县| 达孜县| 夹江县| 新源县| 民乐县| 石台县| 新安县| 扎囊县| 黄石市| 阳西县| 陆河县| 西青区| 汝南县| 加查县| 霍邱县| 崇信县| 涞水县| 双城市| 荆门市| 萨迦县| SHOW| 齐齐哈尔市| 辽阳县| 阳谷县|