An Introduction to C++ Lambdas: What, Why, and How

C++ lambdas are a powerful feature that let you create anonymous functions directly in your code—functions without a name, often used for quick, localized tasks. In this blog, you’ll discover what lambdas are, why they matter, and how to use them with hands-on examples. By the end, you’ll be able to write and experiment with your own C++ lambdas.

What Is a Lambda in C++?

lambda expression in C++ is a concise way to define an inline function object, typically for short-lived operations such as sorting, filtering, or applying an action to each element in a container.

General Syntax:

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

A simple lambda:

auto add = [](int a, int b) { return a + b; };
int sum = add(2, 3); // sum is 5

Why Do We Need Lambdas?

  • Convenience: No need to define a separate function for a one-off task.
  • Clarity: Place logic exactly where it’s used (e.g., in a standard algorithm).
  • Function Objects: Use as arguments to functions that expect callable objects (e.g., std::sortstd::for_each).
  • Capturing Context: Easily capture local variables without global scope pollution.

Common Use Cases

  • Sorting with custom criteria.
  • Filtering data.
  • Applying operations on elements in containers.
  • Handy for event handling and callbacks.

Example: Sorting a Vector With a Lambda

Let’s sort a vector of integers in descending order using a lambda:

#include <vector>
#include <algorithm>
#include <iostream>

int main() {
    std::vector<int> nums = {3, 1, 4, 1, 5, 9};

    std::sort(nums.begin(), nums.end(), [](int a, int b) {
        return a > b;
    });

    for (int n : nums)
        std::cout << n << " ";
    // Output: 9 5 4 3 1 1

    return 0;
}

Interactive Code: Try It Live!

Here’s a small code to play with and enhance your understanding. Copy this into your favorite C++ compiler (or try it on https://www.onlinegdb.com/online_c++_compiler):

#include <algorithm>
#include <vector>
#include <iostream>

int main() {
    std::vector<int> data = {5, 2, 8, 3, 1};

    std::cout << "Original: ";
    for (int n : data) std::cout << n << " ";
    std::cout << "\n";

    // Lambda to filter even numbers
    std::cout << "Even numbers: ";
    std::for_each(data.begin(), data.end(), [](int n) {
        if (n % 2 == 0) std::cout << n << " ";
    });
    std::cout << "\n";

    // Lambda that captures a variable
    int threshold = 4;
    std::cout << "Numbers > " << threshold << ": ";
    std::for_each(data.begin(), data.end(), [threshold](int n) {
        if (n > threshold) std::cout << n << " ";
    });
    std::cout << "\n";
}

Experiment Yourself

  • Try changing the lambda: Sort in ascending order, or print odd numbers instead.
  • Change what gets captured: Replace [threshold] with [&threshold] and modify threshold inside the lambda.

Key Takeaways

  • Lambdas help you write inline, quick functions with access to local variables.
  • They make your code cleaner and more expressive, especially when using STL algorithms.
  • Practice by using lambdas in your next C++ project for sorting, filtering, or callbacks.

Leave a Comment

Your email address will not be published. Required fields are marked *