A lambda function in C++ is a small anonymous function that can be defined inline with the code that uses it. It is similar to a regular function, but does not have a name and can be defined on-the-fly. Lambda functions can capture variables from their enclosing scope, and can be used as arguments to other functions or stored in variables.
Here’s an example of using a lambda function to sort a vector of integers:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v = {5, 2, 8, 1, 9};
// Sort the vector using a lambda function
sort(v.begin(), v.end(), [](int a, int b) {
return a < b;
});
// Print the sorted vector
for (auto x : v) {
cout << x << " ";
}
cout << endl;
return 0;
}
In this example, we define a lambda function inside the sort function call that compares two integers and returns true if the first one is less than the second one. We then pass this lambda function as the third argument to the sort function, which sorts the vector in ascending order.
Lambda functions are particularly useful when we need to define a small piece of code that is only used once, or when we need to customize the behavior of a function in a specific way. They are a powerful feature of modern C++, and can make our code more expressive and concise.