In this tutorial, we will dive into the concept of Lambda Expressions in C++. A lambda expression is a convenient way of defining an anonymous function object right at the location where it is invoked or passed as an argument to a function.
By the end of this tutorial, you should:
Prerequisites
Basic knowledge of C++ syntax and functions is required. Familiarity with the STL (Standard Template Library) will be beneficial but is not necessary.
A lambda expression in C++ has the following syntax:
[capture list] (parameters list) mutable(optional) exception-> return type { //code }
Let's look at some examples:
Example 1: Basic lambda expression
#include<iostream>
using namespace std;
int main() {
auto lambda = []() { cout << "Hello, World!"; };
lambda(); // Invoking the lambda expression to print "Hello, World!"
return 0;
}
Here, auto lambda
is a lambda expression that takes no arguments ()
and has a lambda body that prints "Hello, World!". The lambda expression is invoked with lambda()
.
Expected output:
Hello, World!
Example 2: Lambda with parameters
#include<iostream>
using namespace std;
int main() {
auto lambda = [](int x, int y) { return x + y; };
cout << lambda(5, 7); // Invoking the lambda expression to add 5 and 7
return 0;
}
This lambda expression takes two integers as arguments and returns their sum.
Expected output:
12
Lambda expressions are a powerful feature in C++, allowing you to write inline, anonymous functions. They can improve the readability and maintainability of your code, especially when used with STL algorithms.
The next step to further understand lambda expressions is to practice with more complex examples and different types of capture lists.
Exercise 1: Write a lambda expression that takes an integer and multiplies it by 2.
Solution:
auto lambda = [](int x) { return x * 2; };
cout << lambda(5); // Should print 10
Exercise 2: Write a lambda expression that captures a local variable by value and multiplies it with an argument.
Solution:
int multiplier = 5;
auto lambda = [multiplier](int x) { return x * multiplier; };
cout << lambda(2); // Should print 10
Exercise 3: Write a lambda expression that captures all local variables by reference and modify them inside the lambda body.
Solution:
int value = 5;
auto lambda = [&value]() mutable { value *= 2; };
lambda();
cout << value; // Should print 10
Happy Coding!