C++ Lambda Expressions - Beyond Basics
Lambda expressions are a powerful feature in C++ that allow you to create anonymous functions on-the-fly. While the basics of lambda expressions are relatively straightforward, there are advanced use cases and techniques that can greatly enhance their utility. This guide explores C++ lambda expressions beyond the basics and includes explanations and sample code to illustrate their advanced features.
1. Introduction to Lambda Expressions
Lambda expressions in C++ provide a concise way to define functions locally. They are often used for functions that are short-lived or specific to a particular context.
2. Advanced Lambda Capture
Advanced lambda capture allows you to capture variables by move, capture all local variables by reference, or use capture expressions. Here's an example that demonstrates various capture modes:
#include <iostream>
int main() {
int x = 10;
int y = 20;
auto lambda = [x, &y] {
std::cout << "Captured by value: " << x << std::endl;
std::cout << "Captured by reference: " << y << std::endl;
};
x = 100;
y = 200;
lambda();
return 0;
}
3. Lambda Expressions as Arguments
You can use lambda expressions as arguments to functions or algorithms, which is particularly powerful when working with the Standard Template Library (STL). Here's an example of using a lambda expression with the `std::sort` algorithm:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5}; std::sort(numbers.begin(), numbers.end(), [](int a, int b) {
return a < b;
});
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}
4. Lambda Expressions and Closures
Lambdas can capture and hold local variables, creating closures. Closures are useful when you need to maintain state across multiple calls to the lambda. Here's an example:
#include <iostream>
#include <functional>
int main() {
int total = 0;
std::function<int(int)> adder = [total](int x) mutable {
total += x;
return total;
};
std::cout << adder(10) << std::endl;
std::cout << adder(20) << std::endl;
return 0;
}
5. Conclusion
C++ lambda expressions go beyond being concise inline functions. With advanced capture modes, usage as arguments to functions, and their ability to create closures, they become powerful tools for writing expressive and efficient code. Mastering these advanced features will make your C++ code more flexible and readable.