Lesson 28 of 45 · C++
Lesson 34: Lambda Expressions
Duration: 10 min
Lesson 28 of 45 · C++
Duration: 10 min
cpp\n[ capture ] ( parameters ) -> return_type { body }\n\n- Capture list – [] (nothing), [=] (by copy), [&] (by reference), [x, &y] (mixed).\n- Parameters – can be omitted if deducible.\n- Mutable – allows modifying captured‑by‑copy variables.\n- Generic lambda – use auto in the parameter list (C++14).\n\n---\n\n## Example: Sorting with a lambda that captures a threshold\ncpp\nstd::vector<int> v = {5, 2, 9, 1, 5, 6};\nint threshold = 5;\nstd::sort(v.begin(), v.end(), [threshold](int a, int b) {\n // Elements less than threshold come first, then natural order\n if ((a < threshold) != (b < threshold))\n return a < threshold;\n return a < b;\n});\nfor (int n : v) std::cout << n << ' ';\nstd::cout << '\\n';\n\n\n## Example: Generic lambda that adds two values of any arithmetic type\ncpp\nauto adder = [](auto a, auto b) { return a + b; };\nstd::cout << adder(2, 3) << '\\n'; // int\nstd::cout << adder(2.5, 1.2) << '\\n'; // double\n\n\n> Tip: Use mutable if you need to modify captured values by copy inside the lambda.\n\n---\n\n<Alert type="warning">Avoid capturing large objects by value in performance‑critical lambda loops; prefer reference capture or move them into the lambda.