Search⌘ K
AI Features

Lambdas and Functional Style

Explore how lambda expressions enable inline, unnamed functions in modern C++, making code cleaner and more expressive. Understand capture clauses, use lambdas with standard algorithms like std::sort and std::transform, and learn about functional transformations and context capturing to write flexible, maintainable algorithms.

In earlier lessons, we explored Standard Library algorithms. Many of these algorithms require user-provided logic, such as a custom comparison or an operation to apply to each element. Traditionally, this logic was often implemented as a separate, named function defined far from the point of use. This separation can disrupt readability and clutter the codebase with small, single-purpose helpers.

C++ addresses this problem through lambda expressions. Lambdas allow us to define function objects inline, directly at the call site where they are needed. By keeping behavior close to its usage, lambdas make code more expressive, easier to maintain, and better aligned with the programmer’s intent.

The anatomy of a lambda expression

A lambda expression is an unnamed function defined inline. It creates a temporary object, technically referred to as a closure, that behaves like a callable function. Although the syntax may appear unfamiliar at first, every lambda expression follows a well-defined structure:

A lambda expression is essentially a function that has no name. It creates a temporary object (technically called a closure) that behaves like a function.

[captures] (parameters) -> return_type { body }

Each component serves a specific purpose:

  • Capture clause ([]): Specifies which variables from the surrounding scope are accessible inside the lambda.

  • Parameter list ( ...