Prerequisites:
- Functions in C++
- Map in C++
Maps in C++ are a very useful data structure for storing key-value pairs. A map is the best way to store where we can directly find and access the value using a key with the best time complexity.
However, did you know that you can also store functions as values in a C++ map? That’s right – it is possible to use a map to store and quickly access a set of functions that need to be called at different times in a program. Let’s check the map of functions.
Map of functions
Map of functions is the type of map where rather than the value we attach a function with the key. This can be especially useful if you need to call a variety of functions at different times in your program, as it allows you to easily associate a name with each function and quickly look up and call the function you need.
Syntax:
std::function<return_type(arg_type1, arg_type2, ...)> var_name;
In this code, return_type is the return type of the function, and arg_type1, arg_type2, etc. are the types of the function arguments.
To create a map of functions, we will first need to define the function signature that we want to use. In this case, we want to store functions that take two long arguments and return a long value. We can use the function template from the functional header file to define a variable that can store such a function:
// first create a function template
using func=function<long(long,long)>;
// create a map object
unordered_map<string,func> mp{
{"+", plus<long>()},
{"-", minus<long>()},
{"/", divides<long>()},
{"*", multiplies<long>()}
};
In this code, the functions plus, minus, divide, and multiplies are added to the map object map with string keys “+”, “-“, “/”, and “*”, respectively.
To call a function stored in the map, you can use the array access operator [] to retrieve the function pointer and the function call operator () to call the function.
For example:
long result = map["+"](2, 3); // 5
long result1 = map["-"](2, 3); // -1
long result2= map["*"](2, 3); // 6
long result3 = map["/"](6, 3); // 2
Using a map to store functions has several advantages. It allows you to easily add or remove functions at runtime, and it also allows you to easily associate a name with each function, which can make it easier to understand and maintain the code. Let’s understand it with one problem.
Problem Statement:
You have been given an array of strings called tokens that represent an arithmetic expression written in Reverse Polish Notation (RPN). Your task is to evaluate this expression and return the result as an integer. Each operand may be an integer or another RPN expression. When dividing two integers, the result will always be truncated toward zero. You can assume that the input represents a valid RPN expression and that there will not be any division by zero.
Let us check some test cases to understand.
Case 1:
Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Case 2:
Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22
Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 = 22
Example:
C++
#include <bits/stdc++.h>
using namespace std;
using func = function< long ( long , long )>;
map<string, func> mp{
{ "+" , plus< long >() },
{ "-" , minus< long >() },
{ "/" , divides< long >() },
{ "*" , multiplies< long >() }
};
int evalRPN(vector<string>& A)
{
stack< long > s;
for ( auto i : A) {
if (!mp[i]) {
s.push(stoi(i));
}
else {
auto num1 = s.top();
s.pop();
auto num2 = s.top();
s.pop();
s.push(mp[i](num2, num1));
}
}
return s.top();
}
int main()
{
vector<string> A
= { "10" , "6" , "9" , "3" , "+" , "-11" , "*" ,
"/" , "*" , "17" , "+" , "5" , "+" };
int answer = evalRPN(A);
cout << answer << endl;
return 0;
}
|
Time complexity: O(N) // here N is the size of vector A;
Auxiliary space: O(N).
Similar Reads
map find() function in C++ STL
The std::map::find() is a built-in function in C++ STL that is used to find an element with given key in the map. It is a member function of std::map container so we can directly use it with any map. Syntaxmap_name.find(key)Parameterskey: Key of the pair to be searched in the map container.Return Va
2 min read
map rend() function in C++ STL
The rend() function is an inbuilt function in C++ STL which returns a reverse iterator pointing to the theoretical element right before the first key-value pair in the map(which is considered its reverse end). Syntax: map_name.rend() Parameters:The function does not take any parameter. Return Value:
2 min read
map count() Function in C++ STL
The std::map::count() in C++ is a built-in function that is used to count the occurrence of the given key in the map container. It is the member function of the std::map container. In this article, we will learn how to use std::map::count() in C++. Syntaxmp.count(key) Parameters key: The value whose
2 min read
map erase() Function in C++ STL
In C++, std::map::erase() is a built-in function of std::map container that is used to remove elements from the map using their key or iterator. We can also remove multiple elements using iterators. In this article, we will learn how to use the map::erase() in C++ SyntaxThe std::string::erase() func
3 min read
C String Functions
C language provides various built-in functions that can be used for various operations and manipulations on strings. These string functions make it easier to perform tasks such as string copy, concatenation, comparison, length, etc. The <string.h> header file contains these string functions. T
7 min read
Functors in C++
Please note that the title is Functors (Not Functions)!! Consider a function that takes only one argument. However, while calling this function we have a lot more information that we would like to pass to this function, but we cannot as it accepts only one parameter. What can be done? One obvious an
3 min read
C++ Functions - Pass By Reference
Several ways exist in which data (or variables) could be sent as an argument to a function. Two of the common ones are Passing by Value and Passing by Reference. Passing by reference allows a function to modify a variable without creating a copy. We have to declare reference variables. The memory lo
5 min read
map key_comp() function in C++ STL
The map::key_comp() is a function in STL in C++ that returns a copy of comparison object used by container that compare keys. Syntax: map.key_comp() Return value: This method returns the comparison object used by container that compare keys. Below examples illustrate the working of key_comp() method
2 min read
Passing Pointers to Functions In C++
Prerequisites: Pointers in C++Functions in C++ Passing Pointers to functions means declaring the function parameter as a pointer, at the function calling passing the address of the variable and that address will be stored by a parameter that is declared as a pointer. To change the value of any varia
4 min read
unordered_map count() in C++
The unordered_map::count() is a builtin method in C++ which is used to count the number of elements present in an unordered_map with a given key. Note: As unordered_map does not allow to store elements with duplicate keys, so the count() function basically checks if there exists an element in the un
2 min read