![]() |
VOOZH | about |
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:
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:
Program 2: Below is the C++ program for calling a function with no parameters or a function having two parameters using a function pointer:
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:
Program 3: Below is the program illustrating how lambda expressions can be used for sorting in descending order as well as with absolute values.
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:
Program 4: Below is the program to illustrate the use of a capture list:
sum of the read only variables is : 9 The value of x is 1