Anonymous Functions in C++

Lesson Introduction

Why use anonymous functions in C++? Anonymous functions, known as lambda expressions, help write concise, readable code. They are defined inline without needing a separate function declaration. They're especially useful for short snippets as arguments to algorithms or event handlers.

By the end of this lesson, you'll understand what anonymous functions (lambda expressions) are, how to create them, and how they can simplify your code.

Introduction to Anonymous Functions

Anonymous functions in C++ are functions defined without a name, commonly called lambda expressions. The basic syntax of a lambda expression is:

C++
[capture](parameters) { body };
  • Capture: Specifies which outside variables are accessible in the lambda.
  • Parameters: Function parameters.
  • Body: The actual code to execute.

Simple Example of Anonymous Functions

Consider the following code snippet where we use a lambda function to print elements of a vector. We will put the lambda function into a variable and use it later.

C++
#include <iostream>
#include <vector>

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

    // Lambda to print numbers
    auto print_number = [](int n) {
        std::cout << n << ' ';
    };

    for (int n : numbers) {
        print_number(n);
    }
    // Output: 1 2 3 4 5 

    return 0;
}

Here, print_number is a variable that stores the lambda function that takes an integer n and prints it. This lambda is used in a for loop to print each number in the numbers vector.

Capturing Variables in Lambda

Sometimes, we must access variables from the surrounding scope within your lambda. This is done using the capture clause:

C++
#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    int factor = 2;

    // Lambda capturing the 'factor' variable
    auto multiply_by_factor = [factor](int &n) {
        n *= factor;
    };

    for (int &n : numbers) {
        multiply_by_factor(n);
    }

    for (int n : numbers) {
        std::cout << n << ' ';
    }
    std::cout << '\n';  // Output: 2 4 6 8 10

    return 0;
}

Here, multiply_by_factor is a lambda capturing the factor variable by value. It multiplies each element of the numbers vector by factor.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal