C++ Lambda Expressions & Closures

🔴 Advanced

📖 Definition

Introduced in C++11, a lambda expression ([captures](params) -> return_type { body }) creates an anonymous inline function object (closure) capable of capturing surrounding variables by value or reference.

💡 Code Example

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

int main() {
    std::vector<int> nums{5, 2, 8, 1, 9};

    // Lambda comparison operator passed to std::sort
    std::sort(nums.begin(), nums.end(), [](int a, int b) {
        return a > b; // Descending sort
    });

    for (int n : nums) std::cout << n << " ";
    std::cout << "\n";
    return 0;
}

👀 Output

9 8 5 2 1