Sobes.tech
Junior — Middle

What is the purpose and application of Lambda expressions in programming?

sobes.tech AI

Answer from AI

Lambda expressions are anonymous functions that can be defined directly at the point of use. They allow writing compact and expressive code, especially when working with algorithms, event handling, or callbacks.

Main applications:

  • Passing functions as arguments (e.g., in standard STL algorithms).
  • Local definition of behavior without creating a separate named function.
  • Capturing variables from the surrounding context for convenience in data handling.

Example in C++:

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

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

    // Output numbers greater than threshold using lambda
    std::for_each(numbers.begin(), numbers.end(), [threshold](int n) {
        if (n > threshold) {
            std::cout << n << " ";
        }
    });
    return 0;
}

In this example, the lambda expression captures the variable threshold and is used for filtering and outputting elements.

What is the purpose and application of Lambda… - sobes.tech