Lesson 105 +10 XP

Lambda Expressions

Lambda Expressions

A lambda is an anonymous function you write inline, right where you need it. Lambdas are a staple of modern C++.

The shape

A lambda expression has a capture list, parameters, and a body:

[ /* capture */ ] ( /* parameters */ ) { /* body */ };
  • [] starts the lambda and captures surrounding variables.
  • (...) lists the lambda's parameters.
  • { ... } is the function body - the code to run when the lambda is invoked.

A lambda with std::sort

Here the lambda provides the sorting rule for std::sort:

#include <algorithm>

std::vector<int> v = {8, 3, 5};
std::sort(v.begin(), v.end(), [](int a, int b) {
  return a > b;   // sorts descending
});

The algorithm compares pairs of elements and follows whatever order the lambda tells it.

Captures: by reference and by value

To use variables from the surrounding scope inside a lambda, capture them:

  • [&] captures by reference - the lambda sees and can change the originals.
  • [=] captures by value - the lambda gets copies.
int threshold = 3;
auto bigger = [=](int x) { return x > threshold; };   // threshold copied in

You can also name specific variables: [threshold] captures by value, [&threshold] by reference.

Where lambdas shine

  • Pass behavior to algorithms: std::sort, std::for_each, etc.
  • Write short helpers right where they're used, with no named function definition.
  • A clean alternative to one-off named functions.

TL;DR

  • A lambda is an anonymous function expression.
  • Shape: [capture] (params) { body }.
  • [&] captures by reference; [=] captures by value.
  • Commonly passed as a behavior to std::sort and other algorithms.