From fc0642d17ae3498eaae1fde924ba6a5f9903c1a7 Mon Sep 17 00:00:00 2001 From: Awin Huang Date: Mon, 13 Jun 2022 18:14:14 +0800 Subject: [PATCH] vault backup: 2022-06-13 18:14:14 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Affected files: 02. PARA/03. Resources(資源)/C++17/lambda.md --- .../03. Resources(資源)/C++17/lambda.md | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/02. PARA/03. Resources(資源)/C++17/lambda.md b/02. PARA/03. Resources(資源)/C++17/lambda.md index 9ced500..500b65a 100644 --- a/02. PARA/03. Resources(資源)/C++17/lambda.md +++ b/02. PARA/03. Resources(資源)/C++17/lambda.md @@ -28,7 +28,7 @@ auto comapre = [] (int x, int y) -> bool { ## Lamdba的擷取子句 以中括號開頭的 *lamdba 導入器*可以將外部的變數傳給 Lamdba 運算式,正式名稱是「擷取子句(capture clause)」。 `[=]` 表示它們會以值擷取(captured by value)。Scope內的變數可以在 lamdba 內使用,但是不可以改變。 -`[&]` 表示它們會以址擷取(captured by reference)。Scope內的變數可以在 lamdba 內使用,可以改變。 +`[&]` 表示它們會以參考擷取(captured by reference)。Scope內的變數可以在 lamdba 內使用,可以改變。 ### 以值擷取(captured by value) 假設有一段程式如下: @@ -117,4 +117,22 @@ private: }; ``` -### 以址擷取(captured by reference) \ No newline at end of file +### 以參考擷取(captured by reference) +`[&]` 會擷取 scope 內的所有外部變數,而且可以修改: +```cpp +void testLambda() { + float notUsed = 1.0f; + std::vector numlist{10, 20, 30, 50, 60}; + auto findInRange = [&](int32_t start, int32_t end) { + numlist.push_back(100); // OK + + for (auto num : numlist) { + if (num >= start && num <= end) return true; + } + return false; + }; + + std::cout << "Result: " << findInRange(25, 35) << "\n"; + std::cout << "numlist: " << numlist << "\n"; +} +``` \ No newline at end of file