C++ Lambda Functions - An Overview
C++ lambda functions, also known as lambda expressions, provide a concise way to create small, anonymous functions within your code. Lambdas are especially useful for defining short, local functions that can be used as arguments for algorithms, such as those provided by the Standard Template Library (STL). In this guide, we'll provide an overview of C++ lambda functions and illustrate their usage with sample code.
Syntax of Lambda Functions
A lambda function is defined using the following syntax:
[ capture_clause ] ( parameters ) -> return_type {
// Function body
}
Let's break down the components:
- Capture Clause: Specifies which external variables are accessible within the lambda function.
- Parameters: Defines the parameters that the lambda function takes.
- Return Type: Specifies the return type of the lambda function.
- Function Body: Contains the actual code of the lambda function.
Sample Code: Using Lambda Functions
Let's look at some examples of lambda functions in action:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
// Example 1: A simple lambda
auto greet = []() {
cout << "Hello, Lambda!" << endl;
};
greet();
// Example 2: Lambda with parameters
auto add = [](int a, int b) {
return a + b;
};
int sum = add(5, 3);
cout << "Sum: " << sum << endl;
// Example 3: Lambda as a parameter to STL algorithm
vector<int> numbers = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
int count = count_if(numbers.begin(), numbers.end(), [](int n) {
return n % 2 == 0;
});
cout << "Even numbers count: " << count << endl;
return 0;
}
In this code, we demonstrate three different lambda examples:
- Example 1: A simple lambda with no parameters or return type. It prints a greeting.
- Example 2: A lambda that takes two integers as parameters and returns their sum.
- Example 3: Using a lambda as a parameter to the `count_if` algorithm to count even numbers in a vector.
Capture Clauses
The capture clause determines which external variables the lambda can access. The syntax for capture clauses is as follows:
- [&]: Capture all external variables by reference.
- [=]: Capture all external variables by value.
- [var]: Capture a specific external variable (e.g., `[x]` captures only `x`).
- [&var]: Capture a specific external variable by reference.
- [=, &var]: Capture all external variables by value and a specific one by reference.
Conclusion
C++ lambda functions provide a convenient way to define short, local functions within your code. They are commonly used in situations where you need a small, one-time function without the need to create a separate named function. Understanding lambda functions is essential for modern C++ programming, particularly when working with algorithms and functional-style code.