Open In App

Higher Order Functions in C++

Higher-order functions are functions that take functions as an argument. It is used in functional languages which is not used in C++ are, although this is slowly changing since C++11 gave us lambdas and ‘std::function’… and frequently people don’t realize that ‘std::function’ is not a tool that fills all use cases. In this article, we will explain how to pass a function as an argument to a different calling function.

Syntax:



return_type function_name(function<return_type fun_name(argument_list), other function arguments)

Parameters: In the above function_name takes a function named as fun_name as an argument. Both the function_name and fun_name can have some additional arguments.



Below is the illustration of the same:




// C++ program to illustrate the higher
// order function in C++
#include <bits/stdc++.h>
using namespace std;
 
// Function that will be passed as an
// arguments to calling function
bool Parser(string x)
{
    // Check if string start
    // with alphabet 'R'
    return x[0] == 'R';
}
 
// Function that takes function as
// an arguments
vector<string> Parse(vector<string> a,
                     function<bool(string)> Parser)
{
    vector<string> ans;
 
    // Traverse the vector a
    for (auto str : a) {
        if (Parser(str)) {
            ans.push_back(str);
        }
    }
 
    // Return the resultant vector
    return ans;
}
 
// Driver Code
int main()
{
    vector<string> dict = { "geeks", "Rxop",
                            "Rka", "for" };
 
    // Function Call for Higher
    // Order Functions
    vector<string> ans = Parse(dict, Parser);
 
    // Print the results
    for (auto str : ans) {
        cout << str << " ";
    }
 
    return 0;
}

Output
Rxop Rka

Advantages of Higher Order Functions:

By the use of the higher-order function, many problems can be solved. For Example, to build a function that takes a list and another function as its input applies that function to each element of that list, and returns the new list. In Haskell, this could be done really easily using the inbuilt higher order function called map. Definition of the map is:

map :: (a -> b) -> [a] -> [b]  
map _ [ ] = [ ]
map f (x : xs) = f x : map f xs

Here,


Article Tags :