C++
The page lists some knowledges and features of C++.
Lambda Function
Lambda functions in C++ are a way to create small, anonymous functions on the fly. They were introduced in C++11 and are particularly useful when you need to define a function for a short, one-time use. Lambda functions can capture variables from their enclosing scope and are often used with standard algorithms, such as std::for_each
, std::sort
, and std::transform
. Here's how you define and use lambda functions:
Lambda Syntax
The basic syntax of a lambda function is as follows:
[ capture_clause ] ( parameter_list ) -> return_type {
// Lambda body
}
capture_clause
is used to specify which variables from the enclosing scope the lambda can access. You can capture variables by value, by reference, or a combination of both.parameter_list
is similar to the parameter list of a regular function.return_type
is optional and can be used to specify the return type of the lambda, but it can be deduced by the compiler in most cases.The lambda body contains the code to be executed when the lambda is called.
Example 1: Basic Lambda
#include <iostream>
int main() {
// Define a lambda that takes two integers and returns their sum
auto add = [](int a, int b) {
return a + b;
};
// Use the lambda
int result = add(5, 3);
std::cout << "Result: " << result << std::endl;
return 0;
}
In this example, we define a lambda add
that takes two integers and returns their sum. We then use the lambda to compute the sum of 5 and 3.
Example 2: Lambda with Capture Clause
#include <iostream>
int main() {
int x = 5;
int y = 3;
// Define a lambda that captures 'x' by value and 'y' by reference
auto multiply = [x, &y]() {
return x * y;
};
y = 4; // Modify 'y'
// Use the lambda
int result = multiply();
std::cout << "Result: " << result << std::endl; // Result: 20
return 0;
}
In this example, the lambda multiply captures x by value (so it won't change if x changes) and y by reference (so it reflects changes made outside the lambda).
Example 3: Lambda in Standard Algorithms
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// Use a lambda with std::for_each to print each element
std::for_each(numbers.begin(), numbers.end(), [](int num) {
std::cout << num << " ";
});
return 0;
}
In this example, we use a lambda with std::for_each
to iterate through a vector and print each element.
Lambda functions are a powerful feature of C++ that allow for more concise and readable code, especially when dealing with algorithms and custom operations on data.
Last updated