Sobes.tech
Middle

Tell about lambda functions in C/C++.

sobes.tech AI

Answer from AI

Lambda functions are anonymous inline functions that can be defined and used directly at the call site. They appeared in C++11.

Syntax:

[capture list](parameter list) -> return type {
    // lambda function body
}
  • [capture list] — defines which external variables are accessible inside the lambda and how they are captured (by value [var] or by reference [&var]). [=] captures all by value, [&] captures all by reference. [] means no capture.
  • (parameter list) — similar to the parameter list of a regular function.
  • -> return type — specifies the return type. It can be omitted if the type can be deduced by the compiler (since C++14).
  • {} — contains the executable code of the lambda.

Usage examples:

Sorting with a custom criterion:

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

int main() {
    std::vector<int> numbers = {5, 2, 8, 1, 9};
    
    // Sorting in descending order using a lambda
    std::sort(numbers.begin(), numbers.end(), [](int a, int b) {
        return a > b; // Criterion for descending order
    });

    for (int n : numbers) {
        std::cout << n << " ";
    }
    std::cout << std::endl; // Output: 9 8 5 2 1

    return 0;
}

Using capture:

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

int main() {
    int threshold = 5;
    std::vector<int> numbers = {1, 7, 3, 8, 2, 6};
    
    // Counting elements greater than threshold, capturing threshold by value
    int count = std::count_if(numbers.begin(), numbers.end(), [threshold](int n) {
        return n > threshold;
    });
    
    std::cout << "Count of numbers > " << threshold << ": " << count << std::endl; // Output: Count of numbers > 5: 3

    return 0;
}

Capture by reference to modify an external variable (requires mutable for capture by value):

#include <iostream>

int main() {
    int value = 10;
    
    // Capture value by reference to modify it inside the lambda
    auto modify_value = [&value]() {
        value += 5;
    };

    modify_value();
    
    std::cout << "Modified value: " << value << std::endl; // Output: Modified value: 15

    return 0;
}

Advantages:

  • Conciseness and clarity: Simplify code when the function is needed only in one place.
  • Locality: Defined where used, improving code locality.
  • Variable capture: Easy access to variables from the surrounding context.
  • Efficiency: Often compiled as inline functions, avoiding call overhead.

Disadvantages:

  • Can complicate debugging if used in complex contexts.
  • Excessive use for complex tasks can make the code less readable.