Open In App

Generalized Lambda Expressions in C++14

Last Updated : 18 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Lambda expressions were introduced in C++11. They are basically snippets of code that can be nested inside other functions and even function call statements. By combining a lambda expression with the auto keyword these expressions can then be later used in the program. We have discussed lambda expressions in detail in this article Lambda Expressions in C++. Before proceeding with this article make sure you have either read the linked article, or know about lambda expression semantics like scope capture, return value. C++ 14 buffed up lambda expressions further by introducing what’s called a generalized lambda. To understand this feature let’s take a general example. Suppose we create a lambda function to return the sum of two integers. So our lambda function would look like

[](int a, int b) -> int { return a + b; }

But what if we needed to obtain the sum of two floating point values later on? So we would need to declare another lambda expression that would work for only double values. Similarly each time our input parameters changed in type, the lambda function needed to be rewritten.

[](double a, double b) -> double { return a + b; }

Before C++ 14 there was a way to circumvent this problem by using template parameters,

template<typename T>
[](T a, T b) -> T { return a + b };

C++ 14 does away with this and allows us to use the keyword auto in the input parameters of the lambda expression. Thus the compilers can now deduce the type of parameters during compile time. So, in our previous example, a lambda expression that would work for both integer and floating-point values would be

[](auto a, auto b) { return a + b; }

A very important application of this feature is that enhances existing algorithms greatly. Take for instance the sort() function. The following snippet will sort all data types ( provided they have overloaded < operators) in descending order.

sort(container.begin(), container.end(), 
[](auto i, auto j) -> bool { return i > j; }

Here are a few example programs using generalized lambdas:

Example 1 

CPP




// Cpp program to demonstrate
// generalized lambda expressions
#include <iostream>
#include <string>
 
using namespace std;
int main()
{
 
    // Declare a generalized lambda and store it in sum
    // By using auto keyword it cant be used for recursion
    auto sum = [](auto a, auto b) {
        return a + b;
    };
 
    // Find sum of two integers
    cout << sum(1, 6) << endl;
 
    // Find sum of two floating numbers
    cout << sum(1.0, 5.6) << endl;
 
    // Find sum of two strings
    cout << sum(string("Geeks"), string("ForGeeks")) << endl;
 
    return 0;
}


Output:

7
6.6
GeeksForGeeks

Time Complexity: O(1)
Auxiliary Space: O(1)

Example 2 : 

CPP




// Cpp program to demonstrate
// how to sort integers, floats, strings
// floating data types using a
// generalized lambda and sort function
 
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
 
using namespace std;
 
// Utility Function to print the elements of a collection
void printElements(auto& C)
{
 
    for (auto e : C)
        cout << e << " ";
 
    cout << endl;
}
 
int main()
{
 
    // Declare a generalized lambda and store it in greater
    auto greater = [](auto a, auto b) -> bool {
        return a > b;
    };
 
    // Initialize a vector of integers
    vector<int> vi = { 1, 4, 2, 1, 6, 62, 636 };
 
    // Initialize a vector of doubles
    vector<double> vd = { 4.62, 161.3, 62.26, 13.4, 235.5 };
 
    // Initialize a vector of strings
    vector<string> vs = { "Tom", "Harry", "Ram", "Shyam" };
 
    // Sort integers
    sort(vi.begin(), vi.end(), greater);
 
    // Sort doubles
    sort(vd.begin(), vd.end(), greater);
 
    // Sort strings
    sort(vs.begin(), vs.end(), greater);
 
    printElements(vi);
    printElements(vd);
    printElements(vs);
 
    return 0;
}


Output

636 62 6 4 2 1 1 
235.5 161.3 62.26 13.4 4.62 
Tom Shyam Ram Harry 

Time Complexity: O(N log N)
Auxiliary Space: O(1)

Example 3:

C++




// Cpp program to demonstrate
// how to sort 2D vectors
//using a lambda and sort function
 
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
 
    vector<vector<int>> v={
        {7, 8},
        {1, 2},
        {3, 7},
        {4, 5}
    };
 
    // Sort vectors accordind to their second number using lambda function
      
    sort(v.begin(),v.end(),[](vector<int>&a, vector<int>&b){
        return a[1]<b[1];
    });
   
      // for printing the vector
     
      for(int i = 0 ; i < v.size() ; i++){
      for(int j = 0 ; j < v[0].size(); j++){
        cout<<v[i][j];
      }
    }
       
    return 0;
}


Time Complexity: O(N^2)
Auxiliary Space: O(1)

Note : Generalized Lambda expressions only work for C++ standards 14 and later. The list of compilers that support C++ 14 is given in the references section References: 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads