Lambda Functions in C++


Lambda functions, also known as anonymous functions, are a powerful feature in C++ that allow you to define a function in a concise and readable way. Unlike traditional functions, lambda functions do not have a name and can be defined in-line where they are used.

 

Here's an example that demonstrates how lambda functions can be used in C++:

 

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

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

    // Define a lambda function that returns the square of a number
    auto square = [](int x) { return x * x; };

    // Use the lambda function with the std::transform algorithm
    std::transform(v.begin(), v.end(), v.begin(), square);

    // Print the transformed vector
    for (const auto& x : v) {
        std::cout << x << " ";
    }
    std::cout << std::endl; // outputs "1 4 9 16 25"

    return 0;
}

In this example, we define a lambda function square that takes an integer x and returns its square. We then use the lambda function with the std::transform algorithm to square each element in a vector v.

Lambda functions are especially useful in C++11 and later, where they can be used with auto and the decltype type deduction mechanism. This allows you to define lambda functions that capture variables from the surrounding scope, making them more flexible and reusable.

 

Summary

Lambda functions, also known as anonymous functions, are a powerful feature in C++ that allow you to define a function in a concise and readable way. Unlike traditional functions, lambda functions do not have a name and can be defined in-line where they are used. Lambda functions are especially useful in C++11 and later for their ability to capture variables from the surrounding scope, making them more flexible and reusable.

 

'C++' 카테고리의 다른 글

Compiling C++ Code on a Mac using the Terminal and GCC  (0) 2023.02.10
Key Features of C++14  (0) 2023.02.10
Function Pointers in C++  (0) 2023.02.10
Overview of C++11 and C++14 Features  (0) 2023.02.10
Understanding Functions in C++  (0) 2023.01.12

+ Recent posts