Language: EN

cpp-funciones-lambda

What are Lambda Functions in C++

In C++ a lambda function is a compact syntax for defining anonymous functions, without the need to declare it explicitly as a traditional function.

These functions are especially useful for simple and quick operations. For example, when it comes to operations on collections, such as filtering, mapping, or reducing.

If you want to learn more about Lambda functions
check out the Introduction to Programming Course read more

Syntax of lambda functions

The basic syntax of a lambda function in C++ is as follows:

[capture](parameters) -> return_type { body }
  • Capture: List of environment variables that the lambda can use.
  • Parameters: List of input parameters, separated by commas if there is more than one.
  • Return type: Type of value that the lambda returns, optional if the type is deducible.
  • Body: The code that executes when the lambda is invoked.

Basic example

Here is a basic example of a lambda function that adds two numbers:

#include <iostream>

int main() {
    auto add = [](int x, int y) -> int {
        return x + y;
    };

    std::cout << "Sum: " << add(5, 3) << std::endl; // Output: 8

    return 0;
}

In this example,

  • The lambda function add takes two parameters x and y, and returns their sum.
  • The keyword auto is used to deduce the type of the lambda, and -> int specifies the return type.

Variable capture

Lambda functions can capture variables from the context in which they are defined. There are different capture modes:

  • By value (=): Captures a copy of the variables.
  • By reference (&): Captures the variables by reference, allowing modification of their value.
  • Mixed: Combination of captures by value and by reference.
#include <iostream>

int main() {
    int value = 10;

    auto lambda = [value]() {
        std::cout << "Value: " << value << std::endl;
    };

    lambda(); // Output: Value: 10

    return 0;
}
#include <iostream>

int main() {
    int value = 10;

    auto lambda = [&value]() {
        value++;
        std::cout << "Value: " << value << std::endl;
    };

    lambda(); // Output: Value: 11
    std::cout << "Value after lambda: " << value << std::endl; // Output: Value after lambda: 11

    return 0;
}

Use in higher-order functions

Lambda functions can be passed as arguments to other functions that accept functions or functional objects.

Example with std::function:

#include <iostream>
#include <functional>

void Execute(std::function<void()> func) {
    func();
}

int main() {
    auto message = []() {
        std::cout << "Hello from a lambda function" << std::endl;
    };

    Execute(message);

    return 0;
}

Lambdas capturing this

Lambdas can also capture this to access class members from within the lambda.

#include <iostream>

class MyClass {
private:
    int value;
public:
    MyClass(int v) : value(v) {}
    void printValue() {
        auto lambda = [this]() {
            std::cout << "Value: " << value << std::endl;
        };
        lambda();
    }
};

int main() {
    MyClass obj(42);
    obj.printValue(); // Prints 42
    return 0;
}

In this example, the lambda captures this to access the member value of the class MyClass.

Generic Lambdas

Since C++14 lambdas can be generic, allowing them to work with different data types.

#include <iostream>

int main() {
    auto print = [](auto data) {
        std::cout << data << std::endl;
    };
    print(5);        // Prints an integer
    print(3.14);     // Prints a float
    print("Hello");   // Prints a string
    return 0;
}

In this example, the lambda print is capable of handling different data types thanks to its generic nature.

Practical examples

:::::::