#include #include #include #include #include using namespace std ; class customSort1 { public: bool operator()(int const& s1, int const& s2) { return s1 < s2 ; } }; struct Add { int operator()(int a, int b) const { cout << "Inside Add operator." << endl ; return a + b; } }; int main() { //Using lambda in stl sort algorithm std::array arr1{5, 7, 4, 2, 8, 6, 1, 9, 0, 3}; auto print1 = [&arr1](const string& rem) { for (auto element : arr1) std::cout << element << ' '; std::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 ; }; sort(arr1.begin(), arr1.end(), customSort); print1("sorted with the customSort "); //Inline 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. 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 add3 = add3Object ; add3( 10, 20 ) ; }