在ISO C++11標準中引入了lambda表達式。用於創建並定義匿名的函數對象。以簡化編程工作。Lambda表達式的語法如下:
[函數對象參數] (參數列表)->返回值類型 {函數體};
1.函數對象參數:可以是表達式之前出現過的變量,代表當前Lambda表達式會用到的變量。如果不寫這個變量的話,則在Lambda表達式中就無法訪問這個變量。如果Lambda需要多個變量的話,則每個變量之間用“,”隔開。如果之前所有的變量都能用到,那麼就在[]裏面寫一個“=”即可。
2.參數列表:當前匿名函數的參數表。
3.返回值類型:當前匿名函數的返回值。
4.函數體:當前匿名函數的函數體。
舉個例子:假如我們有一個數組,我們要對數組當中的元素進行降序排列。最簡單的方式就是調用<algorithm>當中的std::sort函數,但是這個函數的第三個參數是一個函數,在C++98標準當中,由於沒有Lambda表達式,我們就得這樣寫:
#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(int a,int b)
{
return a > b;
}
void main()
{
int a[5] = { 1,2,3,4,5 };
cout << "當前數組:";
for (int i = 0; i < 5; i++)
{
cout << a[i] << " ";
}
cout << endl;
sort(a, a + 5, cmp);
cout << "當前數組:";
for (int i = 0; i < 5; i++)
{
cout << a[i] << " ";
}
cout << endl;
system("pause");
}
但是用Lambda表達式的話,我們只需這樣寫:
#include<iostream>
#include<algorithm>
using namespace std;
void main()
{
int a[5] = { 1,2,3,4,5 };
cout << "當前數組:";
for (int i = 0; i < 5; i++)
{
cout << a[i] << " ";
}
cout << endl;
//不同之處在這裏。
sort(a, a + 5, [](int a, int b)->bool{return a > b; });
cout << "當前數組:";
for (int i = 0; i < 5; i++)
{
cout << a[i] << " ";
}
cout << endl;
system("pause");
}
可以看到,使用Lambda表達式可以讓代碼變得更加簡潔。
上面已經說到,如果在Lambda表達式當中需要許多參數,那麼就將這些參數之間用“,”隔開,下面就舉一個這方面的例子:
#include<iostream>
#include<algorithm>
using namespace std;
void main()
{
int num1 = 10;
int num2 = 6;
int a[5] = { 1,2,3,4,5 };
cout << "num1 =" << num1 << "," << "num2 = " << num2 << endl;
cout << "a數組:";
for (int i = 0; i < 5; i++)
{
cout << a[i] << " ";
}
cout << endl;
cout << "將a中每個元素的值都加上(num1+num2)之後:" << endl;
for_each(&a[0], &a[5], [num1, num2](int& x)->void {x += (num1 + num2); });
cout << "a數組:";
for (int i = 0; i < 5; i++)
{
cout << a[i] << " ";
}
cout << endl;
system("pause");
}
如何獲取Lambda表達式的返回值?
代碼舉例:
#include<iostream>
using namespace std;
void main()
{
int(*pFunc)(int, int) = nullptr;//先定義了一個函數指針
pFunc = [](int a, int b)->int {return a + b; };
int num = pFunc(1, 2);
cout << "Lambda表達式的返回值是:" << num << endl;
system("pause");
}
運行結果:
Lambda表達式的返回值是:3