๐ C++ Lambda Expressions โ Modern Functional Programming in C++
๐งฒ Introduction โ Why Lambda Expressions Matter
In modern C++ programming, especially since C++11, the introduction of lambda expressions has empowered developers to write concise, anonymous, and inline functions. Lambdas are crucial for passing logic into STL algorithms, implementing callbacks, and enabling functional programming patterns.
๐ฏ In this guide, youโll learn:
- What lambda expressions are
- How to define and use them
- Capture lists and return types
- Best practices and advanced use cases
๐ Core Concept โ What is a Lambda Expression?
A lambda expression is an anonymous function that can be defined directly in the body of code, allowing you to embed logic inline without a separate function declaration.
๐งฌ Basic Syntax:
[capture](parameters) -> return_type {
// body
};
Components:
- Capture list
[]โ Captures surrounding variables (by value or reference). - Parameters
()โ Input values like a regular function. - Return type
-> typeโ (Optional) specifies return type. - Body
{}โ The executable code.
๐ป Code Examples โ With Step-by-Step Explanations
โ Example 1: Simple Lambda Expression
#include <iostream>
using namespace std;
int main() {
auto greet = []() {
cout << "Hello from lambda!" << endl;
};
greet(); // Call the lambda
return 0;
}
๐ Explanation:
- Declares a lambda with no parameters.
- The
greetvariable holds the lambda function, which is invoked like a normal function.
โ Example 2: Lambda with Parameters and Return
#include <iostream>
using namespace std;
int main() {
auto add = [](int a, int b) -> int {
return a + b;
};
cout << "Sum: " << add(5, 3);
return 0;
}
๐ Explanation:
- Lambda accepts two parameters and returns their sum.
- Return type is optional here but shown explicitly.
โ Example 3: Capturing Local Variables
#include <iostream>
using namespace std;
int main() {
int x = 10;
int y = 20;
auto sum = [x, &y]() {
// x captured by value, y by reference
cout << "x + y = " << x + y << endl;
y += 10; // Modifies original y
};
sum();
cout << "Modified y: " << y;
return 0;
}
๐ Explanation:
xis captured by value (read-only).yis captured by reference, allowing modification.
โ Example 4: Using Lambda with STL Algorithms
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> numbers = {1, 2, 3, 4, 5};
for_each(numbers.begin(), numbers.end(), [](int n) {
cout << n * 2 << " ";
});
return 0;
}
๐ Explanation:
- The lambda doubles each value using
for_each()from the STL.
๐ก Best Practices & Tips
๐ Best Practice
Use lambdas for short, localized logic. For complex tasks, prefer named functions or functors.
๐ก Tip
Capture by reference when you need to modify external variables. Use capture-by-value for safety.
โ ๏ธ Pitfall
Avoid capturing variables by reference if the lambda may outlive the captured context (e.g., in threads).
๐ Lambda Components โ Functional Table
| Component | Description | Example |
|---|---|---|
| Capture List | Specifies variables to capture | [x], [&x], [=], [&] |
| Parameters | Input to the lambda | (int a, int b) |
| Return Type | Optional explicit return type | -> int |
| Body | Function logic | { return a + b; } |
๐ ๏ธ Use Cases & Performance Notes
| Use Case | Why Use Lambda | Example |
|---|---|---|
| STL Algorithms | Cleaner syntax for callbacks | std::for_each, std::sort |
| Event Handling | Inline logic for events | GUI, Qt/GTK, etc. |
| Multi-threading | Pass logic to threads or futures | std::thread([](){}) |
| Functional Patterns | Filtering, mapping, reduction | std::accumulate, std::transform |
๐ Summary โ Recap & Next Steps
Lambda expressions in C++ provide a concise way to define inline, anonymous functions and pass logic to algorithms, threads, and callbacks. They improve code readability and reduce boilerplate.
๐ Key Takeaways:
- Lambdas = anonymous inline functions
- Capture local variables safely
- Ideal for STL, events, and threads
โ๏ธ Next Steps:
Explore generic lambdas (C++14+), mutable lambdas, and lambdas inside classes for more advanced C++ functional programming patterns.
โ FAQ Section
โ What is a lambda in C++?
โ
A lambda is an anonymous inline function introduced in C++11, often used with STL and functional-style programming.
โ Can lambdas return values?
โ
Yes. You can use return just like in regular functions, or specify -> return_type explicitly.
โ What’s the difference between [=] and [&] in capture lists?
โ
[=] captures all local variables by value, [&] by reference.
โ Can lambdas modify captured variables?
โ
Only those captured by reference. For value-captured variables, you can use mutable lambdas to allow modification.
โ Are lambdas faster than regular functions?
โ
Lambdas can be inlined and optimized efficiently by compilers, especially for short operations.
Share Now :
