#include #include #include #include #include using namespace std ; class customSort1 { public: bool operator()(const int& s1, const int& s2) { return s1 < s2 ; } }; class Add { public: int operator()(int a, int b) const { cout << "Inside Add operator." << endl ; return a + b ; } }; int main() { //Using lambda in stl sort algorithm array arr1{5, 7, 4, 2, 8, 6, 1, 9, 0, 3}; auto print1 = [&arr1](const string& rem) { for (auto element : arr1) cout << element << ' '; cout << ": " << rem << '\n'; }; sort(arr1.begin(), arr1.end()); print1("sorted with the default operator<"); auto customSort = [] (int const& s1, int const& s2) -> bool { return s1 > s2 ; }; //Pass a lambda object sort(arr1.begin(), arr1.end(), customSort); print1("sorted with the customSort "); //Inline lambda sort(arr1.begin(), arr1.end(), [] (int const& s1, int const& s2) -> bool { return s1 > s2 ; }); print1("sorted with the inline lambds "); //Using the built in functor "greater" //Signature of the greater is //template struct greater { // bool operator()(const T& lhs, const T& rhs) const; //}; sort(arr1.begin(), arr1.end(), greater() ); //Use a custom functor object customSort1 customSort1Object ; sort(arr1.begin(), arr1.end(), customSort1Object ); print1("Sorted with the functor object."); //Return statements can be implicit or //explicit. //Example of implicit return auto add = [] (int a, int b) { // always returns an 'int' return a + b; }; cout << "add called:" << add(4, 5) << endl ; //Explicit return statement auto add1 = [] (int a, int b ) -> double { return a + b ; }; cout << "add1 called:" << add1(4, 6) << endl ; //inline example // initialize vector of integers vector nums = {1, 2, 3, 4, 5, 8, 10, 12}; int even_count = count_if(nums.begin(), nums.end(), [](int num) { return num % 2 == 0; } ); cout << "There are " << even_count << " even numbers." << endl ; //Without using auto //A lambda is a functor object. //Add add3 = [] (int a, int b) { function add2 = [] (int a, int b) { cout << "Sum: " << a + b << endl ; }; add2(1, 2); Add add3Object ; //Assign a class object to a function object function< int(int, int) > add3 = add3Object ; add3( 10, 20 ) ; /* Add add4Object = [] (int a, int b) { // always returns an 'int' return a + b; }; Compiler Error lambdas2.cpp:143:10: error: conversion from ‘main()::’ to non-scalar type ‘Add’ requested 143 | Expression on the left is of class "Add". Expression on the right is a different class type and due to strong static type checking we cannnot assign a class of one type to a different type. */ } //https://stackoverflow.com/questions/65186151/conversion-from-lambda-to-non-scalar-type-requested