-
Hajipur, Bihar, 844101
Lambda functions in C++ are short, unnamed functions that you can define directly inside your code. They were introduced in C++11 and have become an important part of modern C++ programming. A lambda function is useful when you need a simple operation without defining a full separate function.
They are most often used with the Standard Template Library (STL) algorithms such as sort(), for_each(), and find_if() where a function needs to be passed as an argument. Lambda functions help keep code concise, readable, and organized.
The general syntax of a lambda function in C++ is:
[capture](parameters) -> return_type {
// function body
};
Let’s break it down:
capture: Defines which variables from the surrounding scope can be used inside the lambda.
parameters: The input arguments (just like normal functions).
return_type: Optional, used when the compiler can’t automatically infer the return type.
function body: Contains the logic to execute when the lambda is called.
Here’s a simple example:
#include <iostream>
using namespace std;
int main() {
auto greet = []() {
cout << "Hello, Lambda Function!" << endl;
};
greet();
return 0;
}
Output:
Hello, Lambda Function!
Here, greet is a variable that stores the lambda function and executes it when called.
Lambdas can also take parameters just like regular functions.
#include <iostream>
using namespace std;
int main() {
auto add = [](int a, int b) {
return a + b;
};
cout << "Sum: " << add(10, 5) << endl;
return 0;
}
Output:
Sum: 15
This lambda takes two integer parameters and returns their sum.
One of the most powerful features of lambdas is capturing variables from their surrounding scope.
There are three main ways to capture variables:
Capture by value [=] – The lambda gets a copy of the external variables.
Capture by reference [&] – The lambda can modify the actual external variables.
Capture specific variables – You can choose which variables to capture.
Example:
#include <iostream>
using namespace std;
int main() {
int x = 10, y = 20;
auto captureByValue = [=]() {
cout << "Sum (by value): " << x + y << endl;
};
auto captureByReference = [&]() {
x += 5;
cout << "Updated x (by reference): " << x << endl;
};
captureByValue();
captureByReference();
return 0;
}
Output:
Sum (by value): 30
Updated x (by reference): 15
In the first case, x and y are copied, so changes don’t affect the original variables. In the second case, the reference capture modifies the actual variable x.
Most of the time, C++ automatically determines the return type of a lambda. But if the logic is complex, you can explicitly specify it using the -> operator.
#include <iostream>
using namespace std;
int main() {
auto divide = [](double a, double b) -> double {
return a / b;
};
cout << "Result: " << divide(10, 2) << endl;
return 0;
}
Output:
Result: 5
Here, -> double explicitly states that the lambda will return a double value.
One of the best uses of lambda functions is with STL algorithms. They allow you to define custom logic directly where it’s needed.
Example:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> numbers = {5, 3, 8, 1, 2};
sort(numbers.begin(), numbers.end(), [](int a, int b) {
return a < b;
});
cout << "Sorted numbers: ";
for (int n : numbers) cout << n << " ";
return 0;
}
Output:
Sorted numbers: 1 2 3 5 8
Here, the lambda defines a comparison logic directly inside the sort() function without needing a separate comparator function.
By default, when you capture variables by value ([=]), they are treated as read-only inside the lambda. But using the mutable keyword allows you to modify them.
#include <iostream>
using namespace std;
int main() {
int count = 5;
auto modify = [count]() mutable {
count++;
cout << "Inside lambda: " << count << endl;
};
modify();
cout << "Outside lambda: " << count << endl;
return 0;
}
Output:
Inside lambda: 6
Outside lambda: 5
The lambda modified its internal copy of count, but the original count outside remained unchanged.
Starting from C++14, lambdas can have parameters with the auto keyword, making them generic. This means a single lambda can work with multiple data types.
#include <iostream>
using namespace std;
int main() {
auto print = [](auto value) {
cout << value << endl;
};
print(42);
print(3.14);
print("C++ Lambda");
return 0;
}
Output:
42
3.14
C++ Lambda
This lambda can print integers, floating-point numbers, and strings — all with the same definition.
You can also define a lambda inside another lambda if needed. This feature is useful for creating modular code.
#include <iostream>
using namespace std;
int main() {
auto outer = [](int n) {
auto inner = [](int x) {
return x * x;
};
return inner(n) + 5;
};
cout << "Result: " << outer(4);
return 0;
}
Output:
Result: 21
Here, the outer lambda contains an inner lambda, showing that lambdas can be composed.
Lambda functions are anonymous, inline functions useful for short, reusable code blocks.
They can capture variables from outer scope by value [=] or by reference [&].
The return type can be automatically deduced or explicitly specified using -> type.
Mutable lambdas let you modify captured-by-value variables.
Generic lambdas use auto for flexible type handling.
Widely used with STL algorithms like sort(), for_each(), and find_if() for simplicity and clarity.
Write a lambda function to add two integers and display the result.
Create a lambda that calculates the square of a given number.
Use a lambda inside the sort() function to arrange an array of integers in descending order.
Write a lambda that captures two variables by value and prints their sum.
Create a lambda that captures a variable by reference and modifies its value.
Write a program that uses a lambda to count even numbers in a vector.
Create a generic lambda that prints any type of value (int, double, string).
Write a lambda that returns the maximum of two numbers.
Use a lambda with the for_each() function to print all elements of an array.
Write a program that uses a mutable lambda to increase a captured counter variable each time it is called.