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.
Lesson 34 of 45
C++10 min
Keep these ideas in mind as you work through the lesson.
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.
[ capture ] ( parameters ) -> return_type { body }
[] (nothing), [=] (by copy), [&] (by reference), [x, &y] (mixed).auto in the parameter list (C++14).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 << '\
';
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
mutableif 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.