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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Lesson 34: Lambda Expressions | C++ Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. C++ Course

Lesson 34 of 45

·C++

Lesson 34: Lambda Expressions

10 min

Course progress76%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • Capture list forms
  • Mutable lambdas
  • Generic lambdas (auto parameters)
  • Using lambdas with STL algorithms

Lambda Expressions

Lambdas are unnamed function objects that can capture variables from the surrounding scope. They are perfect for short callbacks, custom comparators, and in‑place transformations.


Syntax breakdown

[ capture ] ( parameters ) -> return_type { body }
  • Capture list – [] (nothing), [=] (by copy), [&] (by reference), [x, &y] (mixed).
  • Parameters – can be omitted if deducible.
  • Mutable – allows modifying captured‑by‑copy variables.
  • Generic lambda – use auto in the parameter list (C++14).

Example: Sorting with a lambda that captures a threshold

std::vector<int> v = {5, 2, 9, 1, 5, 6};
int threshold = 5;
std::sort(v.begin(), v.end(), [threshold](int a, int b) {
    // Elements less than threshold come first, then natural order
    if ((a < threshold) != (b < threshold))
        return a < threshold;
    return a < b;
});
for (int n : v) std::cout << n << ' ';
std::cout << '\
';

Example: Generic lambda that adds two values of any arithmetic type

auto adder = [](auto a, auto b) { return a + b; };
std::cout << adder(2, 3) << '\
';      // int
std::cout << adder(2.5, 1.2) << '\
'; // double

Tip: Use mutable if you need to modify captured values by copy inside the lambda.


<Alert type="warning">Avoid capturing large objects by value in performance‑critical lambda loops; prefer reference capture or move them into the lambda.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from C++ CourseBrowse activities
Previous lessonLesson 33: Algorithms (sort, find, transform, etc.)Continue to lesson 35Lesson 35: Exception HandlingBack to C++ Course curriculum