Open In App

When to Prefer Lambda Expressions over Functors in C++?

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 of a functor in the following cases:

1. Short-lived Functions

When we need to define a function that is only used within a limited scope and doesn’t require reuse elsewhere in the code we can define a lambda expression inline at the point of use and avoid the need to create a separate functor class.

Example

The below example demonstrates the use of lambda expressions for short-lived functions.

C++




// C++ program to use lambda function for short lived
// functions
#include <iostream>
using namespace std;
  
int main()
{
    // Using a lambda expression for a short-lived function
    auto add = [](int a, int b) { return a + b; };
  
    // Using the lambda expression to add two numbers
    int result = add(3, 4);
  
    cout << "Result of addition: " << result << endl;
  
    return 0;
}


Output

Result of addition: 7

2. Inline Callbacks

When passing a callback function to an algorithm or library function we can simply define a lambda expression directly at the call site.

Example

The below example demonstrates the use of lambda expressions in inline callbacks.

C++




// C++ program to use lambda function for inline callbacks
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
  
int main()
{
    // Using a lambda expression as an inline callback for
    // for_each
    vector<int> numbers = { 1, 2, 3, 4, 5 };
  
    for_each(numbers.begin(), numbers.end(),
             [](int x) { cout << x << " "; });
  
    cout << endl;
  
    return 0;
}


Output

1 2 3 4 5 

3. Algorithm Customization

When customizing the behavior of standard algorithms such as sort, transform, or for_each we can pass a lambda expression as an argument to the algorithm to specify the desired behavior.

Example

The below example demonstrates the use of lambda expressions for algorithm customization.

C++




// C++ program to use lambda function for algorithm
// customization.
  
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
  
int main()
{
    // Using a lambda expression to customize transform
    vector<int> numbers = { 1, 2, 3, 4, 5 };
    vector<int> squared;
  
    transform(numbers.begin(), numbers.end(),
              back_inserter(squared),
              [](int x) { return x * x; });
  
    // Output the squared numbers
    for (int num : squared) {
        cout << num << " ";
    }
  
    cout << endl;
  
    return 0;
}


Output

1 4 9 16 25 

4. Concise Function Objects

When the functor’s logic is simple and doesn’t require maintaining internal state or complex behavior we can use lambda expressions to define lightweight function objects inline.

Example

The below example demonstrates the use of lambda expressions for concise function object for simplicity.

C++




// C++ program to use lambda function for simplicity and
// concise function objects
  
#include <iostream>
using namespace std;
  
int main()
{
    // Using a lambda expression for a concise function
    // object
    auto multiplyByTwo = [](int x) { return x * 2; };
  
    // Using the lambda expression to multiply a number by
    // two
    int result = multiplyByTwo(8);
  
    cout << "Result of multiplication: " << result << endl;
  
    return 0;
}
  
// This code is contributed by Susobhan Akhuli


Output

Result of multiplication: 16

5. Capturing Variables from Local Scope

When we need to capture and access variables from the enclosing scope we can use the capture list [&] or [=] to capture variables by reference or value, respectively, allowing the lambda expression to access and modify the captured variables.

Example

The below example demonstrates the use of lambda expressions for capturing variables from local scope.

C++




// C++ program to use lambda function for capturing
// variables from local scope.
  
#include <iostream>
using namespace std;
  
int main()
{
    int externalVariable = 42;
  
    // Using a lambda expression to capture and modify an
    // external variable
    auto modifyVariable
        = [&externalVariable]() { externalVariable *= 2; };
  
    modifyVariable();
  
    // Output the modified variable
    cout << "Modified variable: " << externalVariable
         << endl;
  
    return 0;
}
  
// This code is contributed by Susobhan Akhuli


Output

Modified variable: 84


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads