Lambda Functions in C++

Understand what lambda functions are, their syntax, and examples in C++.

Lambda Functions in C++ Interview with follow-up questions

Question 1: What is a lambda function in C++?

Answer:

A lambda function in C++ is an anonymous function that can be defined inline within a code block. It is a way to create a function object without explicitly defining a separate function. Lambda functions are mainly used for writing concise and readable code.

Back to Top ↑

Follow up 1: Can you explain with an example?

Answer:

Sure! Here's an example of a lambda function in C++:

#include 
#include 
#include 

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

    // Using a lambda function to multiply each number by 2
    std::transform(numbers.begin(), numbers.end(), numbers.begin(), [](int n) { return n * 2; });

    // Printing the modified numbers
    for (int number : numbers) {
        std::cout << number << " ";
    }

    return 0;
}

Output:

2 4 6 8 10
Back to Top ↑

Follow up 2: What is the syntax of a lambda function?

Answer:

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

[capture_list](parameters) -> return_type { function_body }
  • capture_list: It is an optional list of variables that the lambda function can capture from the surrounding scope. It can be used to access variables outside the lambda function.
  • parameters: It is an optional list of parameters that the lambda function can accept.
  • return_type: It is the return type of the lambda function. If not specified, the return type is automatically deduced by the compiler.
  • function_body: It is the body of the lambda function, which contains the code to be executed.
Back to Top ↑

Follow up 3: What are the benefits of using lambda functions?

Answer:

There are several benefits of using lambda functions in C++:

  1. Concise code: Lambda functions allow you to write shorter and more readable code by eliminating the need for defining separate functions.
  2. Flexibility: Lambda functions can be defined inline within a code block, making it easier to express small and simple operations without cluttering the code with additional function definitions.
  3. Capturing variables: Lambda functions can capture variables from the surrounding scope, allowing you to use them within the lambda function.
  4. Standard algorithms: Lambda functions are often used with standard algorithms like std::sort, std::transform, etc., to provide custom behavior without the need for defining separate function objects.
  5. Performance: Lambda functions can sometimes improve performance by avoiding the overhead of function calls, especially when used with algorithms that can be optimized by the compiler.
Back to Top ↑

Question 2: How can you capture variables in a lambda function?

Answer:

In a lambda function, you can capture variables from the surrounding scope by value or by reference. To capture variables by value, you can use the '=' sign followed by the variable name. To capture variables by reference, you can use the '&' sign followed by the variable name. For example:

int x = 10;

// Capture by value
auto lambda1 = [=]() {
    // use x
};

// Capture by reference
auto lambda2 = [&]() {
    // use x
};
Back to Top ↑

Follow up 1: What is the difference between capture by value and capture by reference?

Answer:

The difference between capture by value and capture by reference in a lambda function is how the captured variables are accessed and modified. When capturing by value, a copy of the variable is made, and any modifications made inside the lambda function do not affect the original variable. When capturing by reference, the lambda function directly accesses and modifies the original variable.

Capture by value is useful when you want to preserve the value of the variable at the time the lambda function is created, while capture by reference is useful when you want to modify the original variable or have multiple lambda functions share the same variable.

It's important to note that when capturing by reference, you need to ensure that the captured variable remains valid for the lifetime of the lambda function. If the captured variable goes out of scope, accessing it inside the lambda function will result in undefined behavior.

Back to Top ↑

Follow up 2: Can you provide an example of each?

Answer:

Sure! Here are examples of capturing variables by value and by reference:

int x = 10;

// Capture by value
auto lambda1 = [=]() {
    // use x
    x = 20; // This does not affect the original x
};

// Capture by reference
auto lambda2 = [&]() {
    // use x
    x = 20; // This modifies the original x
};
Back to Top ↑

Question 3: Can lambda functions be used with standard algorithms in C++?

Answer:

Yes, lambda functions can be used with standard algorithms in C++. Lambda functions provide a convenient way to define small, inline functions that can be used as arguments to algorithms. They are especially useful when you need to perform a simple operation on each element of a container or when you need to define a custom comparison function for sorting or searching.

Back to Top ↑

Follow up 1: Can you provide an example of using a lambda function with a standard algorithm?

Answer:

Certainly! Here's an example of using a lambda function with the std::transform algorithm to square each element of a vector:

#include 
#include 
#include 

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

    std::transform(numbers.begin(), numbers.end(), std::back_inserter(squaredNumbers), [](int n) {
        return n * n;
    });

    for (int num : squaredNumbers) {
        std::cout << num << ' ';
    }

    return 0;
}

Output:

1 4 9 16 25
Back to Top ↑

Follow up 2: What are the benefits of using lambda functions with standard algorithms?

Answer:

Using lambda functions with standard algorithms offers several benefits:

  1. Readability: Lambda functions allow you to define the operation or comparison logic inline, making the code more concise and easier to understand.

  2. Flexibility: Lambda functions can capture variables from their surrounding scope, allowing you to use and modify variables from the enclosing function within the lambda.

  3. Customization: Lambda functions provide a way to customize the behavior of standard algorithms by defining custom operations or comparison functions.

  4. Code reuse: Lambda functions can be used as arguments to multiple algorithms, allowing you to reuse the same logic in different contexts.

Overall, using lambda functions with standard algorithms can lead to more expressive and maintainable code.

Back to Top ↑

Question 4: What is a generic lambda and how is it used in C++?

Answer:

A generic lambda is a lambda function in C++ that can accept arguments of different types. It is used to write generic code that can operate on multiple types without the need for explicit template parameters. Generic lambdas make use of the auto keyword to deduce the types of the arguments at compile time. They are defined using the lambda syntax with the auto keyword as the parameter type. For example:

auto myLambda = [](auto x) { return x * 2; };
Back to Top ↑

Follow up 1: Can you provide an example of a generic lambda?

Answer:

Sure! Here's an example of a generic lambda that adds two numbers:

auto addLambda = [](auto x, auto y) { return x + y; };
Back to Top ↑

Follow up 2: What are the benefits of using generic lambdas?

Answer:

There are several benefits of using generic lambdas in C++:

  1. Code reusability: Generic lambdas allow you to write code that can operate on multiple types without the need for explicit template parameters. This promotes code reusability and reduces code duplication.

  2. Improved readability: Generic lambdas make the code more readable by eliminating the need for explicit type declarations. The use of the auto keyword allows the compiler to deduce the types of the lambda arguments, making the code more concise and easier to understand.

  3. Flexibility: Generic lambdas provide flexibility by allowing you to write code that can handle different types of arguments. This can be useful in scenarios where the exact type of the arguments is not known in advance.

Overall, generic lambdas are a powerful feature in C++ that enable you to write more generic and flexible code.

Back to Top ↑

Question 5: Can lambda functions be stored and passed as arguments in C++?

Answer:

Yes, lambda functions can be stored and passed as arguments in C++. Lambda functions are essentially anonymous functions that can be defined inline. They can be assigned to variables and passed as arguments to other functions, just like any other function pointer or object.

Here is an example of storing a lambda function in a variable:

auto myLambda = [](int x) { return x * 2; };
Back to Top ↑

Follow up 1: How can you store a lambda function in a variable?

Answer:

To store a lambda function in a variable, you can use the auto keyword to automatically deduce the lambda's type. Here is an example:

auto myLambda = [](int x) { return x * 2; };
Back to Top ↑

Follow up 2: Can you provide an example of passing a lambda function as an argument to another function?

Answer:

Yes, here is an example of passing a lambda function as an argument to another function:

#include 
#include 

void performOperation(int x, std::function operation) {
    int result = operation(x);
    std::cout << "Result: " << result << std::endl;
}

int main() {
    int value = 5;
    performOperation(value, [](int x) { return x * 2; });
    return 0;
}

In this example, the performOperation function takes an integer x and a lambda function operation as arguments. The lambda function is then called with the value of x and the result is printed.

Back to Top ↑