Welcome to the exciting world of C++ Lambda Syntax! This tutorial is designed to help you understand Lambda functions, their importance, and how to use them effectively in your C++ projects.
Lambda functions, also known as anonymous functions, are a C++ feature that allows you to write functions inline without the need for a name. They can capture and store references to local variables.
Lambda functions offer several benefits:
The syntax for a lambda function in C++ is as follows:
[ capture clause ] ( parameters ) -> return_type { function body }The capture clause defines the variables that the lambda function will capture and store. It can be of three types:
[ ]: No capture (no variables are captured)[ = ]: Capture by copy (all local variables are captured by value)[ & ]: Capture by reference (all local variables are captured by reference)[ =, &a ]: Capture a by copy and other local variables by referenceJust like regular functions, lambda functions can have parameters and a return type. If no return type is specified, the default return type is auto.
Let's create a simple lambda function that calculates the square of a number:
#include <iostream>
#include <functional>
int main() {
auto square = [](int num) -> int { return num * num; };
int result = square(5);
std::cout << "The square of 5 is: " << result << std::endl;
return 0;
}Lambda functions can be used with standard algorithms like std::sort. Here's an example that sorts a list of numbers in ascending order and another that sorts them in descending order:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {5, 3, 1, 4, 2};
std::sort(numbers.begin(), numbers.end());
std::cout << "Sorted in ascending order:\n";
for (int num : numbers) {
std::cout << num << ' ';
}
std::reverse_copy(numbers.begin(), numbers.end(), numbers.begin());
std::cout << "\nSorted in descending order:\n";
for (int num : numbers) {
std::cout << num << ' ';
}
return 0;
}What does the capture clause `[ & ]` do in a lambda function?
That's it for this lesson! With this knowledge, you're now ready to explore the power of Lambda functions in C++. Happy coding! š