diff --git a/02. PARA/03. Resources(資源)/C++17/lambda.md b/02. PARA/03. Resources(資源)/C++17/lambda.md index 6598a50..bc72cac 100644 --- a/02. PARA/03. Resources(資源)/C++17/lambda.md +++ b/02. PARA/03. Resources(資源)/C++17/lambda.md @@ -27,10 +27,27 @@ auto comapre = [] (int x, int y) -> bool { ## Lamdba的擷取子句 以中括號開頭的 *lamdba 導入器*可以將外部的變數傳給 Lamdba 運算式,正式名稱是「擷取子句(capture clause)」。 -[=] 表示它們會以值擷取(captured by value)。 -[&] 表示它們會以址擷取(captured by reference)。 +`[=]` 表示它們會以值擷取(captured by value)。 +`[&]` 表示它們會以址擷取(captured by reference)。 ### 以值擷取(captured by value) -假設有一個function如下: +假設有一段程式如下: +```cpp +void testLambda() { + float notUsed = 1.0f; + std::vector numlist{10, 20, 30, 50, 60}; + auto findInRange = [=](int32_t start, int32_t end) { + for (auto num : numlist) { + if (num >= start && num <= end) return true; + } + return false; + }; + + std::cout << "Result: " << findInRange(25, 35) << "\n"; +} +``` + +用`[=]`可以用來擷取 lamdba scope範圍所及的變數,沒有在 Lamdba 運算式裡面被用到的變數舊部會被擷取,例如 `float notUsed = 1.0f;`。 + ### 以址擷取(captured by reference) \ No newline at end of file