Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C++ Course

Lesson 28 of 45 · C++

Lesson 34: Lambda Expressions

Duration: 10 min

Lambda Expressions\n\nLambdas are unnamed function objects that can capture variables from the surrounding scope. They are perfect for short callbacks, custom comparators, and in‑place transformations.\n\n---\n\n## Syntax breakdown\ncpp\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.

Previous: Lesson 33: Algorithms (sort, find, transform, etc.)Next: Lesson 35: Exception Handling