Skip to content

Lambda

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.

auto add = [](int a, int b)
{
return a + b;
};
CaptureMeaning
[]Không capture
[&]Capture tất cả bằng reference
[=]Capture tất cả bằng copy
[x, &y]x copy, y reference
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;
});
auto print = [](const auto& value) {
std::cout << value << '\n';
};
  • Capture reference tới biến hết lifetime.
  • Capture [=] rồi tưởng mọi thứ đều immutable.
  • Comparator cho sort không tạo strict weak ordering.

lambda hàm ẩn danh capture list generic lambda comparator