Lambda Expressions vs Function Pointers
Last Updated :
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 function
int descending(int x, int y)
{
return x > y;
}
// Absolute value sorting function
int absolute(int x, int y)
{
return abs(x) > abs(y);
}
// Driver Code
int 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;
}
Output: 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 parameter
void fun()
{
cout << "GeeksforGeeks\n";
}
// Function having two parameters
// and a return type
int add(int x, int y)
{
return x + y;
}
// Driver Code
int 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;
}
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 Code
int 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;
}
OutputBefore 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 Code
int 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;
}
Output: sum of the read only variables is : 9
The value of x is 1
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read