Lambda
Quick Notes
Section titled “Quick Notes”Lambda là function object viết tại chỗ. Capture list quyết định lambda thấy biến bên ngoài như thế nào. Rất hữu ích với STL algorithms và callback ngắn.
Syntax
Section titled “Syntax”auto add = [](int a, int b){ return a + b;};Captures
Section titled “Captures”| Capture | Meaning |
|---|---|
[] | Không capture |
[&] | Capture tất cả bằng reference |
[=] | Capture tất cả bằng copy |
[x, &y] | x copy, y reference |
Example
Section titled “Example”std::vector<int> v = {3, 1, 2};
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b;});
int limit = 2;auto count = std::count_if(v.begin(), v.end(), [limit](int x) { return x >= limit;});Generic Lambda
Section titled “Generic Lambda”auto print = [](const auto& value) { std::cout << value << '\n';};Common Mistakes
Section titled “Common Mistakes”- Capture reference tới biến hết lifetime.
- Capture
[=]rồi tưởng mọi thứ đều immutable. - Comparator cho
sortkhông tạo strict weak ordering.
Search Keywords
Section titled “Search Keywords”lambda hàm ẩn danh capture list generic lambda comparator