C++學習_lambda表達式_八

lambda表達式

很多語言都有增加了lambda表達式,我沒想到c++也增加了,lambda表達式是一個不錯的語法糖

基本結構

[] () mutable throw() -> int 
{
    
    
}

捕獲子句[]

這個東西是用來捕獲外部變量的

不捕獲任何變量

#include <iostream>
#include <string>

using namespace std;

int main() {
    int a = 123;
    auto func = []() {
        cout << "hello lambda exp";
    };
    func();
    return 0;
}

捕獲一個變量

#include <iostream>
#include <string>

using namespace std;

int main() {
    int a = 123;
    auto func = [a]() {
        cout << a;
    };
    func();
    return 0;
}

捕獲所有變量的拷貝

拷貝就說明變量在表達式內部只可讀而不可更改(即使更改,這個更改也不會傳遞到外部),當然值傳遞只能捕獲在lambda函數之前的變量

#include <iostream>
#include <string>

using namespace std;

int main() {
    int a = 123;
    int b = 456;
    string c = "tinuv";
    auto func = [ = ]() {
        cout << a << "\n";
        cout << b << "\n";
        cout << c << "\n";
        cout << d;
    };
    func();
    return 0;
}

引用捕獲

#include <iostream>
#include <string>

using namespace std;

int main() {
    int a = 123;
    int b = 456;
    auto func = [ &a, &b ]() {
        cout << a << "\n";
        cout << b << "\n";
        b = 10;
    };
    a = 678;
    func();
    cout << b;
    return 0;
}

輸出結果是

678
456
10

除此之外還可以捕獲this指針,這主要在面向對象中使用,這裏不介紹

mutable關鍵字

如果不使用mutable關鍵字的話,修改值傳遞的變量是會報錯的,但如果使用mutable關鍵字的話就可以更改值傳遞的變量了,但是,即使修改了也==不能傳遞到外部==

#include <iostream>
#include <string>

using namespace std;

int main() {
    int a = 123;
    int b = 456;
    auto func = [a, b]()mutable {
        cout << a << "\n";
        cout << b << "\n";
        b = 10;
        cout << b << "\n";
    };
    func();
    cout << b;
    return 0;
}

throw()子句

這裏暫時不介紹

參數列表,返回類型,函數主體

都跟其他語言的差不多,就不多說了

??正文結束??
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章