Lambda Expressions vs Function Pointers - GeeksforGeeks

01 Oct, 2021
Function Pointer: A function pointer, or a subroutine pointer, or a procedure pointer, is a pointer that points to a function. In simple words, it is a pointer to the location inside the text section. It stores the address of a function and is used for passing a behavior as a parameter to another function.
For instance, if someone wants to sort a container like a vector, or lists, and uses the STL sort( ), but doesn’t wish to sort it in ascending order, which is the default parameter, in that case, pass a behavior to the sort function, which is actually the function pointer, and get his data sorted.
Program 1: Below is the C++ program to implement the above concept:
C++
// C++ program to implement the above// concepts#include <bits/stdc++.h>using namespace std; // Descending order sorting functionint descending(int x, int y){    return x > y;} // Absolute value sorting functionint absolute(int x, int y){    return abs(x) > abs(y);} // Driver Codeint main(){    // Stores integers in the vector    vector<int> vect = { 2, 8, -5, -9,                         0, 12, 5 };     cout << "Sorting with descending "         << "order as parameter\n";     // Stores the address of descending    // order function in the funnptr    // function pointer    auto funptr = descending;     // Pass pointer in the actual function    sort(vect.begin(), vect.end(), funptr);     // Print the vector    for (auto i : vect)        cout << i << " ";     cout << "\n";     cout << "Sorting with absolute order"         << " as parameter \n";     // Store the address of the absolute    // value function in the funnptr1    // function pointer    auto funptr1 = absolute;     // Pass pointer in actual function    sort(vect.begin(), vect.end(), funptr1);     // Print the vector    for (auto i : vect) {        cout << i << " ";    }     return 0;}
Sorting with descending order as parameter
12 8 5 2 0 -5 -9 
Sorting with absolute order as parameter 
12 -9 8 5 -5 2 0
 
Why do we need function pointers? A Function pointer is used for the following purposes:
It can store the address of a function.
Like normal pointers, a function pointer can be passed to a function.
It can be used in qsort( ), a C programming library function for sorting, as well as sort( ), a C++ STL library function for sorting.
It can be used to implement Virtual Functions.
Program 2: Below is the C++ program for calling a function with no parameters or a function having two parameters using a function pointer:
C++
// C++ program to implement the above// concepts#include <iostream>using namespace std; // Function having no parametervoid fun(){    cout << "GeeksforGeeks\n";} // Function having two parameters// and a return typeint add(int x, int y){    return x + y;} // Driver Codeint main(){    // Function pointer declaration    // for a function having no *    // return type and no parameter     // note that this is the standard    // syntax used for declaring a    // function pointer    void (*funptr)() = fun;     // auto funptr = fun; can also be    // used     // Calling the function pointer    funptr();     cout << "\n";     // Function pointer declaration    // for a function having int as    // return type and two int parameter     int (*funptr1)(int, int) = add;     // Calling the function pointer    int x = funptr1(4, 6);    cout << x;     return 0;}
GeeksforGeeks

10
 
Lambda Expressions: Lambda Expressions were introduced in C++11. The reason behind the introduction of this was to remove the complexity or cumbersomeness that was faced while using the function pointer. For using function pointers, there is a need to create a separate function. After that, create a function pointer to that function, and then pass it as a parameter to the required function.
As the tasks performed by using function pointers are very small, hence it is not worth writing so many lines of code. Thus, Lambda expressions make it easier to do the same job.
A Lambda expression is also called an anonymous function. It is an expression contained within the main function and helps while passing a behavior as a parameter to a function. In the default case, it does not have access to any of the variables present within the main function. To get access to those, it is required to make some modifications to the capture list of the expressions.
Syntax:
[ capture list ]( parameters ) -> {        // Body};
Constructs of a Lambda Expression: 
[ ]: capture list
( ): parameter
->: arrow
.: return type
{ }: function body
Program 3: Below is the program illustrating how lambda expressions can be used for sorting in descending order as well as with absolute values.
C++
// C++ program to illustrate the// above concept#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){    vector<int> vect{ -1, -6, 4, 2, 0,                      6, 3, 9, -5 };     cout << "Before sorting : \n";    for (auto i : vect) {        cout << i << " ";    }     cout << "\n";     cout << "Sorting in descending "         << "order \n";    sort(vect.begin(), vect.end(),         [](int a, int b) {             return a > b;         });     for (auto i : vect)        cout << i << " ";     cout << "\n";     cout << "Sorting with absolute "         << "value as parameter\n ";    sort(vect.begin(), vect.end(),         [](int a, int b) {             return abs(a) > abs(b);         });     for (auto i : vect)        cout << i << " ";     cout << "\n";     return 0;}
Before sorting : 
-1 -6 4 2 0 6 3 9 -5 
Sorting in descending order 
9 6 4 3 2 0 -1 -5 -6 
Sorting with absolute value as parameter
 9 6 -6 -5 4 3 2 -1 0 
Note: While writing a lambda expression, by default, there will be no access to the variables within which the expression is written. So, to get access to those variables, there is a need to make the following changes in the capture list of the lambda expressions.
Capture list in Lambda expression:
[ ]: Capture nothing.
[ = ]: Capture everything by value. It gives only read access.
[ & ]: Capture everything by reference. It gives both read and write access.
[ =, & x]: Capture everything by value, and x variable by reference.
[ =x, & ]: Capture everything by reference, and x by value.
Program 4: Below is the program to illustrate the use of a capture list:
C++
// C++ program to illustrate the above// concept#include <iostream>using namespace std; // Driver Codeint main(){    int x = 0, a = 5, b = 4;     // In the below lambda expression,    // everything is captured by value,    // and only x by reference    auto fun = [=, &x](int x) {         // If one tries to manipulate        // the value of a read only        // variable, then it causes        // a compilation error.        x++;         // c is a new variable under        // the fun expression which        // sums up a and b        int c = a + b;         cout << "sum of the read only "             << "variables is : " << c             << "\n";         return x;    };     cout << "The value of x is " << fun(x);     return 0;}
sum of the read only variables is : 9
The value of x is 1
 
This article is contributed by Kartik Suman.
sumankartik8
sweetyty
surindertarika1234
Functions
Pointers
C++
C++ Programs
Pointers
Functions
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
Sorting a Map by value in C++ STL