diff --git a/02. PARA/03. Resources(資源)/C++17/lambda.md b/02. PARA/03. Resources(資源)/C++17/lambda.md index 500b65a..6d74033 100644 --- a/02. PARA/03. Resources(資源)/C++17/lambda.md +++ b/02. PARA/03. Resources(資源)/C++17/lambda.md @@ -122,10 +122,10 @@ private: ```cpp void testLambda() { float notUsed = 1.0f; - std::vector numlist{10, 20, 30, 50, 60}; - auto findInRange = [&](int32_t start, int32_t end) { + std::vector numlist{ 10, 20, 30, 50, 60 }; + auto findInRange = [&](int32_t start, int32_t end) { // Use & here numlist.push_back(100); // OK - + for (auto num : numlist) { if (num >= start && num <= end) return true; } @@ -133,6 +133,47 @@ void testLambda() { }; std::cout << "Result: " << findInRange(25, 35) << "\n"; - std::cout << "numlist: " << numlist << "\n"; + std::cout << "numlist: "; + for (auto n : numlist) { + std::cout << n << " "; + } + std::cout << "\n"; // Output numlist: 10 20 30 50 60 100 } -``` \ No newline at end of file +``` + +但是直接參考全部的外部變數不是好的作法,這讓你有機會做出一些意外的修改,所以請擷取有需要的變數就好: +```cpp +void testLambda() { + float notUsed = 1.0f; + std::vector numlist{ 10, 20, 30, 50, 60 }; + + auto findInRange = [&numlist](int32_t start, int32_t end) { + numlist.push_back(100); // OK + + for (auto num : numlist) { + if (num >= start && num <= end) return true; + } + return false; + }; + + ... +} +``` + +如果有多個變數需要擷取,那就用 `,` 分開: +```cpp +auto findInRange = [&numlist, &var1, &var2](int32_t start, int32_t end) { + ... +}; +``` + +### 混合 +以值擷取跟參考擷取也可以寫在一起: +```cpp +auto findInRange = [=, &numlist](int32_t start, int32_t end) { + ... +}; +``` + +上面的例子中,`numlist` 會是一個參考擷取,其他的外部變數則是以值擷取。 +或是: