C++ Lambda Expressions Tutorial

Lambda expressions in C++ provide a way to create anonymous functions, making your code more concise and functional-style.

Basic Syntax


// Lambda Syntax: [capture](parameters) { body }
auto add = [](int a, int b) {
    return a + b;
};
std::cout << add(2, 3); // Outputs: 5
                

Capturing Variables

You can capture variables from the surrounding scope:


int x = 10, y = 20;
auto sum = [x, y]() {
    return x + y;
};
std::cout << sum(); // Outputs: 30
                

Mutable Lambdas

To modify captured variables, use the mutable keyword:


int num = 5;
auto increment = [num]() mutable {
    return ++num;
};
std::cout << increment(); // Outputs: 6
                

Generic Lambdas

With C++14, lambdas can be made generic using auto:


auto multiply = [](auto a, auto b) {
    return a * b;
};
std::cout << multiply(3, 4.5); // Outputs: 13.5
                

Applications

  • Sorting: Use lambdas for custom sorting.
  • Callbacks: Provide inline functions as arguments.
  • Concurrency: Combine lambdas with threading.
0 Interaction
2.5K Views
Views
48 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home