Home Item 5 - Lambda expression 匿名函數 (中文)
Post
Cancel

Item 5 - Lambda expression 匿名函數 (中文)

Lambda expression 匿名函數

你覺得幫 function 取名字很麻煩嗎 ? 我也是 ! 哈 有時候只是處理資料算平均,不寫 function 覺得醜,寫了function 還要想名字, 甚至 c++ 中還要在 header 中宣告 cpp 中實作,實在非常煩!

在 C++11 中,Lambda 表達式是一種匿名函數,通常用於需要臨時函數對象的情況。它們在處理 STL 算法、事件處理和回調函數等方面特別有用 !!!

基本語法

Lambda 表達式的基本語法如下

1
[capture](parameters) -> return_type { body }
  1. capture:指定哪些變量(以及如何捕獲)可以在 Lambda 表達式中使用。
  2. parameters:Lambda 表達式的參數列表,類似於普通函數的參數。
  3. return_type:可選的返回類型。如果可以推斷出返回類型,可以省略。
  4. body:函數體。

1 簡單的 Lambda 表達式

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

int main() {
    auto add = [](int a, int b) -> int {
        return a + b;
    };

    int result = add(5, 3);
    std::cout << "5 + 3 = " << result << std::endl;  // 輸出: 5 + 3 = 8

    return 0;
}

在這個示例中,add 是一個 Lambda 表達式,它接收兩個整數並返回它們的和。

改上述的例子示範省略 return_type

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int main() {
    auto add = [](int a, int b){
        return a + b;
    };

    int result = add(5, 3);
    std::cout << "5 + 3 = " << result << std::endl;

    return 0;
}

上述兩個結果如下:

Desktop View

2 捕獲變量

此時參數列表就不用填入,因為由 capture 部分帶入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int main() {
    int x = 10;
    int y = 20;

    auto addXY = [x, y]() -> int {
        return x + y;
    };

    std::cout << "x + y = " << addXY() << std::endl;  // 輸出: x + y = 30

    return 0;
}

同樣的,如果可以推斷出返回類型,可以省略。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int main() {
    int x = 10;
    int y = 20;

    auto addXY = [x, y](){
        return x + y;
    };

    std::cout << "x + y = " << addXY() << std::endl;  // 輸出: x + y = 30

    return 0;
}

上述兩個結果如下:

Desktop View

3 在 STL 算法中使用 Lambda 表達式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {101, 102, 103, 104, 105};

    std::for_each(numbers.begin(), numbers.end(), [](int n) {
        std::cout << n << " ";
    });


    std::cout << std::endl;

    // sort by descending order
    std::sort(numbers.begin(), numbers.end(), [](int a, int b) {
        return b < a;
    });

    std::for_each(numbers.begin(), numbers.end(), [](int n) {
        std::cout << n << " ";
    });

    return 0;
}

結果如下 Desktop View

在這個示例中,Lambda 表達式被用作 std::for_eachstd::sort 的回調函數。第一個 Lambda 表達式用於輸出向量中的每個元素,第二個 Lambda 表達式用於按降序排序。

使用時機

  1. STL 算法:如 std::for_eachstd::sortstd::transform 等,常常需要回調函數,Lambda 表達式在這些場景中特別方便。
  2. 事件處理:如 GUI 編程中的事件回調函數。
  3. 臨時小函數:當需要簡單的小函數,但不想為其命名時。
  4. 並行與異步編程:如在使用並行庫或異步編程時,Lambda 表達式可以作為任務或回調提交。

以上,感謝讀到最後!

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍