C++ lambda表達式複習

#include
#include<array>
#include<vector>
#include<algorithm>
using namespace std;


int main()
{
//最簡單的lambda表達式
[](){};
//lambda表達式也就是一個函數,我們可以把它賦給函數指針,也可以在後面加上括號使用。
//
//[]裏面可以添加一些限制lambda塊語句中使用外部變量的限制符。一共有四種情況:
//1.空白表示不能對外部變量進行讀寫。
//2.=表示可以對外部變量進行讀訪問。
//3.&表示可以對外部變量進行讀寫訪問。
//4.可以同時填寫&變量名或不加&的變量名,加了&的變量可以進行讀寫,不加&的變量只能進行讀訪問。
//
//()裏面是函數的參數。
//
//{}裏面是函數的表達式。


//例一:將lambda表達式賦予函數指針
void(*p)(int);
p = [](int num){ cout << num << endl; };
p(1);


//例二:將lambda表達式用作函數
[](int num){cout << num << endl; };
[](int num){cout << num << endl; }(1);


//例三:對外部變量進行訪問
int temp1 = 10, temp2 = 20;
//auto tempa = [=](){cout << temp1 << endl << temp2 << endl; };//此時只能對temp1和temp2進行讀訪問。
//tempa();
//auto tempb = [&](){temp1 = 20; temp2 = 10; cout << temp1 << endl << temp2 << endl; };//此時可以對temp1和temp2進行讀寫訪問,注意:此時讀寫的變量爲原本變量。
//tempb();
//auto tempc = [&temp1, temp2](){temp1 = 30; cout << temp1 << endl << temp2 << endl; };//此時可以對temp1進行讀寫訪問,但是隻能對temp2進行讀訪問。
//tempc();
//auto tempd = [=]()mutable{temp1 = 20; temp2 = 10; cout << temp1 << endl << temp2 << endl; };//此時可以對temp1和temp2進行讀寫訪問,但是temp1和temp2是原來變量的副本。


/*
lambda表達式可以允許在函數內再次定義函數(匿名函數),lambda表達式對數據結構的遍歷格外好用。
*/


//例四:用lambda表達式對數組進行訪問
int arr1[5] = { 1, 2, 3, 4, 5 };
for_each(arr1, arr1 + 5, [](int num){cout << num << endl; });


array<int, 5> arr2 = { 1, 2, 3, 4, 5 };
for_each(arr2.begin(), arr2.end(), [](int num){cout << num << endl; });


cin.get();
return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章