C++

C++ : Lambda Expression And Callback Functions

Lambda Expression
- Lambda expression ( lambda ) was introduced in C++11 for easily defining an anonymous function object.
- Lambdas normally have just a few lines of code.
- Lambdas are passed as an argument to APIs ( as callbacks ) or to algorithmic functions.

Lambda Syntax     For details refer
[ captures ] ( parameters ) lambda-specifiers requires ( optional ) { body of function }

[ captures ] : capture clause is used in lambda expression to provide access to variables in the surrounding scope.
     Ex : [&] indicates that all the surrounding variables used inside the body of the function are captured by reference.
     Ex : [=] indicates that all the surrounding variables used inside the body of the function are captured by value.

( parameters ) : the list of parameters that are passed to the lambda expression.

lambda-specifiers requires : these components are optional. The lambda-specifiers could be specifiers ( ex: mutable ), exception ( ex : throw ) or trailing return type ( ex : -> int )

Example :
auto lambda_square = [ ] ( int num ) -> void { std :: cout << "Number : " << num << " Square : " << num * num << std :: endl; };

Callback Functions
- A callback function is a function that is passed as an argument to another function.
- Callback functions are of two types :
       Synchronous callback : A callback function that gets executed immediately and completes its execution before the execution of the calling function.
       Asynchronous callback : A callback function that completes its execution after the execution of the calling function.
- Callbacks can be implemented using function objects.

#include <algorithm>
#include <cctype>
#include <string>
#include <iostream>

int main() {

    std :: string str_ = "AUstralian FrencH WimBleDon Us";
    std :: cout << "Mixed case string : " << str_ << std :: endl;

    // Declare lambda
    auto lambda_to_lower = [] ( unsigned char c ) { return std :: tolower(c); };
    auto lambda_to_upper = [] ( unsigned char c ) { return std :: toupper(c); };

    // Converting a string to lower case using transform algorithm and a lambda expression.
    std :: transform (str_.begin(), str_.end(), str_.begin(), lambda_to_lower); 
    std :: cout << "String lowercase : " << str_ << std :: endl;

    // Converting to upper case
    std :: transform (str_.begin(), str_.end(), str_.begin(), lambda_to_upper); 
    std :: cout << "String uppercase : " << str_ << std :: endl;

    return 0;
}

Output

Mixed case string : AUstralian FrencH WimBleDon Us
String lowercase : australian french wimbledon us
String uppercase : AUSTRALIAN FRENCH WIMBLEDON US
#include<iostream>
#include<vector>
#include<functional>
#include<cstdlib>

// Below Calculate functions takes a vector and 2 lambda functions in the argument list.
void Calculate (const std :: vector<int>& vec_num, const std :: function< void (int) >& calculate_square, 
                                                   const std :: function< void (int) >& calculate_cube) {
     for (const auto& num : vec_num) {
          if (num % 2 == 0) {
              calculate_square (num); 
          } else {
              calculate_cube (num); 
          }
     }   
}

int main() {

    // Seed the random function.
    srand(time(NULL));

    std :: vector<int> vec_num;

    for (int i=0; i<10; i++) {
         vec_num.push_back(rand() % 20);
    }   
 
    /* []  - Capture list
       ()  - Parameter list
       -> return_type - return type
       {}  - Body of lambda function */
            
    auto lambda_square = [] (int num) -> void { std :: cout << "Number : " << num << " Square : " << num * num << std :: endl; };
    auto lambda_cube   = [] (int num) -> void { std :: cout << "Number : " << num << " Cube   : " << num * num * num << std :: endl; };

    Calculate (vec_num, lambda_square, lambda_cube);

    return 0;
}

Output

Number : 6 Square : 36
Number : 9 Cube   : 729
Number : 5 Cube   : 125
Number : 5 Cube   : 125
Number : 15 Cube   : 3375
Number : 12 Square : 144
Number : 4 Square : 16
Number : 14 Square : 196
Number : 14 Square : 196
Number : 0 Square : 0


Copyright (c) 2019-2024, Algotree.org.
All rights reserved.