Lambda là hàm vô danh inline, thường dùng cùng STL algorithm.
cpp
// Cú pháp: [capture](params) -> return_type { body }
auto add = [](int a, int b) { return a + b; };
// Capture clause — truy cập biến ngoài scope:
int base = 10;
auto addBase = [base](int x) { return base + x; }; // by value
auto addBase2 = [&base](int x) { return base + x; }; // by reference
// [=] bắt tất cả by value; [&] bắt tất cả by reference
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });Lưu ý: capture by reference khi lambda tồn tại lâu hơn biến captured → dangling reference.
Dùng capture by value hoặc std::shared_ptr để an toàn.
A lambda is an anonymous inline function, commonly used with STL algorithms.
cpp
// Syntax: [capture](params) -> return_type { body }
auto add = [](int a, int b) { return a + b; };
// Capture clause — access variables from outer scope:
int base = 10;
auto addBase = [base](int x) { return base + x; }; // by value
auto addBase2 = [&base](int x) { return base + x; }; // by reference
// [=] capture all by value; [&] capture all by reference
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });Watch out: capturing by reference when the lambda outlives the captured variable → dangling reference.
Use by-value capture or std::shared_ptr for safety.