Welcome back to CodeYourCraft! Today, we're diving into the world of C++ Lambda Expressions. These are powerful tools introduced in C++11 that let you write small, anonymous functions without actually defining them. Let's explore how they can make your code cleaner and more efficient!
Lambda Expressions are a part of C++11 that allows you to create function objects inline, without defining them separately. They're often used for writing small, one-off functions or to replace function pointers.
[ capture_clause ] ( parameters ) -> return_type
{
// function body
}In the above syntax,
capture_clause: Variables captured from the enclosing scope (optional)parameters: Function arguments (optional)return_type: Type of the function return value (optional)function body: The code that gets executedLet's create a simple lambda function that calculates the square of a number.
#include <iostream>
#include <functional>
int main()
{
// Create a lambda function that squares its input
auto square = [](int num) -> int { return num * num; };
// Use the lambda function
int result = square(5);
std::cout << "The square of 5 is: " << result << std::endl;
return 0;
}Lambda functions can capture variables from the enclosing scope if needed. This allows them to access and modify variables outside their scope.
#include <iostream>
#include <functional>
int main()
{
int counter = 0;
// Create a lambda function that increments the counter
auto incrementCounter = [](){ ++counter; };
// Use the lambda function several times
for(int i = 0; i < 10; ++i)
{
incrementCounter();
}
std::cout << "The counter is: " << counter << std::endl;
return 0;
}Lambda functions can be assigned to different types based on their capture clause and return type.
using IntLambda = std::function<int(int)>;
IntLambda squareLambda = [](int num) -> int { return num * num; };Lambda functions can be used in various scenarios, such as sorting, filtering, and transforming data in STL containers.
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
int main()
{
std::vector<int> numbers = {1, 4, 9, 16, 25};
// Sort the numbers in ascending order
std::sort(numbers.begin(), numbers.end(), [](int a, int b) { return a < b; });
// Print the sorted numbers
for(const auto& number : numbers)
{
std::cout << number << " ";
}
return 0;
}What is the purpose of Lambda Expressions in C++11?
Which of the following is not a part of the Lambda Expression syntax?