Certainly! Lambda functions in C++ are a powerful feature that allows you to create anonymous functions on the fly. They are particularly useful for short-lived operations like passing a simple function as an argument to other functions (e.g., in the Standard Template Library (STL) algorithms) or for defining thread behaviors.
Here's a step-by-step tutorial on lambda functions in C++:
Syntax of a Lambda Function
[capture](parameters) -> return_type {
// function body
};
Components Explained
- Capture List (
[capture]): Specifies which variables from the surrounding scope are accessible inside the lambda.
- Parameters
(parameters): Similar to regular functions, these are the input parameters.
- Return Type (
-> return_type): Optional. Specifies the return type of the lambda. If omitted, the compiler will deduce the return type.
- Function Body: The code that runs when the lambda is called.
Example Usage
Let's go through several simple examples to understand the basics:
Basic Lambda without Capture
#include <iostream>
int main() {
auto greet = []() {
std::cout << "Hello, World!" << std::endl;
};
greet(); // Output: Hello, World!
return 0;
}
Lambda with Parameters
#include <iostream>
int main() {
auto add = [](int a, int b) -> int {
return a + b;
};
std::cout << "Sum: " << add(3, 4) << std::endl; // Output: Sum: 7
return 0;
}
Lambda with Return Type Deduction
#include <iostream>
int main() {
auto multiply = [](int a, int b) {
return a * b; // The compiler deduces the return type as int
};
std::cout << "Product: " << multiply(3, 4) << std::endl; // Output: Product: 12
return 0;
}
Lambda with Capture by Value
#include <iostream>
int main() {
int x = 10;
auto printX = [x]() {
std::cout << "x = " << x << std::endl;
};
x = 20; // This does not affect the lambda because x is captured by value
printX(); // Output: x = 10
return 0;
}
Lambda with Capture by Reference
#include <iostream>
int main() {
int x = 10;
auto printX = [&x]() {
std::cout << "x = " << x << std::endl;
};
x = 20; // This affects the lambda because x is captured by reference
printX(); // Output: x = 20
return 0;
}
Advanced Usage: Capturing All Variables
- Capture All by Value (
[=]): Captures all local variables in the scope by value.
- Capture All by Reference (
[&]): Captures all local variables in the scope by reference.
- Mixed Captures: You can capture some variables by value and others by reference explicitly.
#include <iostream>
int main() {
int a = 5, b = 10;
auto captureAllByValue = [=]() {
std::cout << "a = " << a << ", b = " << b << std::endl;
};
auto captureAllByReference = [&]() {
std::cout << "a = " << a << ", b = " << b << std::endl;
};
auto mixedCapture = [=, &b]() {
std::cout << "a = " << a << ", b = " << b << std::endl;
b = 20;
};
a = 15;
b = 30;
captureAllByValue(); // Output: a = 5, b = 10
captureAllByReference(); // Output: a = 15, b = 30
mixedCapture(); // Output: a = 5, b = 30
std::cout << "b after mixedCapture = " << b << std::endl; // Output: b after mixedCapture = 20
return 0;
}
Using Lambdas with STL Algorithms
Lambda functions are commonly used with STL algorithms for concise and expressive code:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
std::for_each(numbers.begin(), numbers.end(), [](int n) {
std::cout << n * n << " "; // Output: 1 4 9 16 25
});
std::cout << std::endl;
return 0;
}
Lambda as Function Parameters
Often, lambda functions are passed as arguments to other functions:
#include <iostream>
#include <vector>
#include <algorithm>
void applyFunction(const std::vector<int>& vec, const std::function<void(int)>& func) {
for (int v : vec) {
func(v);
}
}
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
applyFunction(numbers, [](int n) {
std::cout << n * 2 << " "; // Output: 2 4 6 8 10
});
std::cout << std::endl;
return 0;
}
Conclusion
Lambda functions are a flexible and concise way to define small, unnamed functions right where you need them. They enhance readability and maintainability when used appropriately. This tutorial should give you a solid foundation to begin using lambdas effectively in your C++ projects.