When to Use Lambda Expressions Instead of Functions in C++?
Last Updated :
18 Mar, 2024
In C++, both lambda expressions and functions are used to define operations that can be invoked somewhere else in the code. However, there are some cases where using lambda expressions can be more beneficial than using functions. In this article, we will learn when to use lambda expressions instead of functions in C++.
When to Prefer Lambda Expressions Instead of Functions?
The following are the cases where using lambda expression in place of functions is more advantageous:
1. Inline Definitions
Lambda expressions can be defined inline where they are used which makes the code more readable as the operation is defined exactly where it is invoked while the functions can only be defined in the global scope.
Example:
C++
// C++ program to illustrate the use of lambda function for
// inline definitions
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Initialize a vector of integers
vector<int> nums = { 1, 2, 3, 4, 5 };
// Use for_each algorithm to iterate over each element
// of the vector and print it
for_each(nums.begin(), nums.end(),
[](int n) { cout << n << " "; });
return 0;
}
2. Short-Lived Operations
If an operation is only used in a limited scope and doesn’t need to be reused elsewhere, a lambda expression can be a more concise option than using functions.
Example:
C++
// C++ program to illustrate the use of lambda function for
// short-lived functions
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vec = { 1, 2, 3, 4, 5 };
cout << "Even Numbers: ";
// Use for_each algorithm to iterate over each element
// of the vector
for_each(vec.begin(), vec.end(), [](int x) {
// Check if the element is even and print it if true
if (x % 2 == 0) {
cout << x << " ";
}
});
cout << endl;
return 0;
}
3. Capturing Local Variables
Lambda expressions can capture local variables from their enclosing scope, which isn’t possible with normal functions and it is very useful when the operation depends on some local state.
C++
// C++ program to illustrate the use of lambda function for
// capturing local variables
#include <iostream>
using namespace std;
int main()
{
// Define a local variable
int multiplier = 5;
// Define a lambda function capturing the local variable
// 'multiplier'
auto multiply
= [multiplier](int n) { return n * multiplier; };
// Call the lambda function and print the result
cout << "3 multiplied by 5 is " << multiply(3) << endl;
return 0;
}
Output3 multiplied by 5 is 15
4. Passing as Function or Template Arguments
Many standard library algorithms like std::sort
, std::transform
,
std::count_if
that
take functions as arguments there lambda expressions can be used to pass custom operations to these algorithms. Some of the data container also require the custom function in some cases so we can use the lamda expression here too.
C++
// C++ program to illustrate the use of lambda function by
// passing as function arguments
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Define a vector of integers
vector<int> nums = { 1, 2, 3, 4, 5 };
// Use count_if algorithm to count the number of even
// numbers in the vector
cout << "Count of even numbers: "
<< count_if(nums.begin(), nums.end(),
[](int n) { return n % 2 == 0; })
<< endl;
return 0;
}
OutputCount of even numbers: 2
5. Creating Function Objects
Lambda expressions are essentially unnamed function objects and they can be stored and passed around like objects, and invoked later which is useful for creating callbacks or deferred operations.
C++
// C++ program to illustrate the use of lambda function for
// creating function objects
#include <functional>
#include <iostream>
using namespace std;
int main()
{
// Define a function object using std::function that
// holds a lambda function
function<void()> printHello
= []() { cout << "Hello, World!" << endl; };
// Call the lambda function through the function object
printHello();
return 0;
}
Conclusion
In conclusion, while functions are a fundamental part of C++, lambda expressions provide a more flexible and convenient way to define operations, especially for short-lived, inline, or local-scope operations.
Similar Reads
When to Prefer Lambda Expressions over Functors in C++? In C++, lambda expressions and functors (function objects) both are used for defining anonymous or named functions in C++. In this article, we will learn when to use a lambda expression instead of a functor in C++. When to Prefer Lambda instead of Functors?Prefer to use a lambda expression instead o
4 min read
When to Use a Functor Instead of a Function in C++? In C++, both functors and functions can be used to encapsulate behavior and provide callable objects. Still, there are specific scenarios where using a functor is more advantageous than a regular function. In this article, we will learn when to use a functor instead of a function in C++. When to Pre
4 min read
Lambda Expressions vs Function Pointers Function Pointer: A function pointer, or a subroutine pointer, or a procedure pointer, is a pointer that points to a function. In simple words, it is a pointer to the location inside the text section. It stores the address of a function and is used for passing a behavior as a parameter to another fu
7 min read
Recursive lambda expressions in C++ A recursive lambda expression is the process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using a recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Ha
8 min read
How to Capture Pairs in Lambda Expression in C++? In C++, lambda expressions provide an easy way to define anonymous functions inline. They also allow these inline functions to capture some variables from the surrounding scope. In this article, we will learn how to capture pairs in lambda functions in C++ Capture Pairs in Lambda Expressions in C++W
2 min read
When to Use List Instead of Vector in C++? In C++, both std::vector and std::list are sequence containers that can store a collection of elements. However, they have different characteristics and use cases. In this article, we will learn when to use a list instead of a vector in C++. When to Prefer List Instead of Vector?Vectors are sequence
4 min read
How to Capture std::vector in Lambda Function? In C++, lambda functions allow users to define an inline function anywhere in the program. They are also able to capture the objects from outside its definition. In this article, we will look at how to capture a std::vector object in lambda functions in C++. Capture std::vector in Lambda FunctionTo
2 min read
When to Use Vector Instead of Array in C++? In C++, both arrays and vectors are used to store collections of data. Arrays are a basic fixed-size sequence of elements, whereas vectors are part of the C++ STL and offer dynamic sizing and more flexibility. There are some cases where using vectors can be more beneficial than using arrays. In this
4 min read
How to Pass an Array into a Lambda Function in C++? In C++, a lambda function, also known as a lambda expression, is a way of defining an anonymous function object right at the location where it is invoked or passed as an argument to a function. In this article, we will learn how to pass an array into a lambda function in C++. Passing an Array into a
2 min read
How to Sort using Member Function as Comparator in C++? In C++, sorting is a common operation that can be customized by providing a comparator function. When working with classes, we might need to sort objects based on their member variables. Using a member function as a comparator is a good technique to achieve this.In this article, we will learn how to
3 min read