Lambda Expressions in C++

 


1️⃣ What is a Lambda Function?

A Lambda function (also called an anonymous function) is a small function that has no name and can be defined inside another function.

Used for short, temporary functions.
Eliminates the need for separate function declarations.
Commonly used in algorithms, threading, and event handling.


2️⃣ Syntax of Lambda Expression

[ capture_list ] ( parameters ) -> return_type {
    // Function body
};

🔹 Breakdown of Syntax

Capture List ([]) → Captures variables from surrounding scope.
Parameter List (()) → Defines input parameters.
Return Type (-> return_type) → Specifies the return type (optional).
Function Body ({}) → Contains the logic.


3️⃣ Example: Basic Lambda Function

#include <iostream>
using namespace std;

int main() {
    auto greet = []() {
        cout << "Hello from Lambda!" << endl;
    };

    greet();  // Calling the lambda function

    return 0;
}

🔹 Output

Hello from Lambda!

Lambda function greet has no parameters and prints a message.
The auto keyword automatically deduces the lambda type.


4️⃣ Example: Lambda with Parameters and Return Type

#include <iostream>
using namespace std;

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

    cout << "Sum: " << add(5, 3) << endl;

    return 0;
}

🔹 Output

Sum: 8

✅ The lambda function add takes two integers and returns their sum.


5️⃣ Capture List ([]): Accessing External Variables

A lambda function can capture variables from the surrounding scope using [ ].

🔹 Types of Capture Modes

1️⃣ Capture by Value ([=]) – Copies variables inside lambda (read-only).
2️⃣ Capture by Reference ([&]) – Uses variables directly (modifiable).
3️⃣ Mixed Capture ([x, &y])x is captured by value, y by reference.


Example 1: Capture by Value ([=])

#include <iostream>
using namespace std;

int main() {
    int x = 10;

    auto lambda = [=]() {  // Captures x by value
        cout << "x = " << x << endl;
    };

    lambda();
    
    return 0;
}

🔹 Output

x = 10

Captured by value ([=]), so x remains unchanged.


Example 2: Capture by Reference ([&])

#include <iostream>
using namespace std;

int main() {
    int x = 10;

    auto lambda = [&]() {  // Captures x by reference
        x += 5;
        cout << "Modified x = " << x << endl;
    };

    lambda();
    cout << "Outside x = " << x << endl;

    return 0;
}

🔹 Output

Modified x = 15
Outside x = 15

Captured by reference ([&]), so changes reflect outside the lambda.


Example 3: Capture Specific Variables

#include <iostream>
using namespace std;

int main() {
    int a = 10, b = 20;

    auto lambda = [a, &b]() {
        // a is captured by value (cannot be modified)
        // b is captured by reference (can be modified)
        // a += 5;  // ❌ ERROR: a is read-only
        b += 5;    // ✅ OK: b is modified
    };

    lambda();
    cout << "b = " << b << endl;

    return 0;
}

🔹 Output

b = 25

Captured a by value (unchangeable) and b by reference (modifiable).


6️⃣ Example: Lambda Function inside std::sort()

#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int arr[] = {5, 2, 8, 1, 3};

    sort(arr, arr + 5, [](int a, int b) {
        return a > b;  // Sort in descending order
    });

    for (int num : arr) {
        cout << num << " ";
    }

    return 0;
}

🔹 Output

8 5 3 2 1

Lambda function used as a custom comparator inside std::sort().


7️⃣ Summary

Lambda expressions allow writing short, inline functions without a name.
Capture List ([]) lets lambdas access external variables.
Great for functional programming, sorting, and event-driven programming.

Would you like an example using lambdas with C++ threads? 🚀

Post a Comment

0 Comments