C++11 Lambda函数(匿名函数)
生活随笔
收集整理的這篇文章主要介紹了
C++11 Lambda函数(匿名函数)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
C++11引入了lambda表達式,使得程序員可以定義匿名函數,該函數是一次性執行的,既方便了編程,又能防止別人的訪問。
Lambda表達式的引入標志,在‘[]’里面可以填入‘=’或‘&’表示該lambda表達式“捕獲”(lambda表達式在一定的scope可以訪問的數據)的數據時以什么方式捕獲的,‘&’表示一引用的方式;‘=’表明以值傳遞的方式捕獲,除非專門指出。 Lambda表達式的參數列表 Mutable 標識 異常標識 返回值 “函數”體,也就是lambda表達式需要進行的實際操作???
// lambda.cpp : 定義控制臺應用程序的入口點。 //#include "stdafx.h" #include <iostream> using namespace std;int _tmain(int argc, _TCHAR* argv[]) {int x = 10, y = 3, z;z = [=]() mutable throw() -> int { int n = x + y; x = y; y = n; return n; }();cout << z << endl; cout << "x:" << x << "\t" << "y:" << y << endl;return 0; }
Lambda表達式的語法通過下圖來介紹:
// lambda.cpp : 定義控制臺應用程序的入口點。 //#include "stdafx.h" #include <iostream> using namespace std;int _tmain(int argc, _TCHAR* argv[]) {int x = 10, y = 3, z;z = [=]() mutable throw() -> int { int n = x + y; x = y; y = n; return n; }();cout << z << endl; cout << "x:" << x << "\t" << "y:" << y << endl;return 0; }
總結
以上是生活随笔為你收集整理的C++11 Lambda函数(匿名函数)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 3000次超长寿命国产闪存 致态512G
- 下一篇: C++ Applications