Open In App

When to Use Lambda Expressions Instead of Functions in C++?

Last Updated : 18 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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;
}

Output
1 2 3 4 5 

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;
}

Output
Even Numbers: 2 4 

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;
}

Output
3 multiplied by 5 is 15

4. Passing as Function or Template Arguments

Many standard library algorithms like std::sortstd::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;
}

Output
Count 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;
}

Output
Hello, World!

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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads