map + function instead of if - else

Using map + function instead of if-else has the following benefits:

  1. The code is more concise: using map + function can convert multiple if-else statements into one line of code, making the code look more concise and easy to understand.

  2. Better readability: Using map + function can abstract the judgment logic into a function, making the code more readable and maintainable.

  3. Easy to expand: When new judgment conditions need to be added, it is only necessary to add a new branch to the function without modifying a large number of if-else statements.

  4. Higher performance: Using map + function can take advantage of the features of functional programming to make the code more efficient. Compared with if-else statements, map + function can be processed faster.

In short, using map + function can make the code more concise, easy to read, easy to expand, and have higher performance.

#include <iostream>
#include <map>
using namespace std;

// 定义函数指针类型
typedef int (*funcPtr)(int);

// 定义函数实现
int func1(int x) {
    
    
    return x * 2;
}

int func2(int x) {
    
    
    return x + 10;
}

int func3(int x) {
    
    
    return x - 5;
}

int main() {
    
    
    // 初始化一个map,键为整数,值为相应的函数指针
    map<int, funcPtr> myMap = {
    
    {
    
    1, &func1}, {
    
    2, &func2}, {
    
    3, &func3}};

    // 测试输入值和对应的函数编号
    int x = 5;
    int funcNum = 1;

    // 使用map和函数指针调用相应的函数
    int result = (*myMap[funcNum])(x);

    cout << "The result is " << result << endl;

    return 0;
}
#include <iostream>
#include <map>
using namespace std;

// 定义函数指针类型
typedef int (*funcPtr)(int);

// 定义函数实现
int func1(int x) {
    
    
    return x * 2;
}

int func2(int x) {
    
    
    return x + 10;
}

int func3(int x) {
    
    
    return x - 5;
}

int main() {
    
    
    // 初始化一个map,键为整数,值为相应的函数指针
    map<int, funcPtr> myMap = {
    
    {
    
    1, &func1}, {
    
    2, &func2}, {
    
    3, &func3}};

    // 测试输入值和对应的函数编号
    int x = 5;
    int funcNum = 1;

    // 使用map和函数指针调用相应的函数
    int result = (*myMap[funcNum])(x);

    cout << "The result is " << result << endl;

    return 0;
}

In this sample code, we first define three functions func1, func2 and func3 to simulate different processing logic. We then use a map to associate input values ​​with corresponding function pointers. Finally, we take out the corresponding function pointer from the map according to the input function number, and call the corresponding function through the pointer to get the result.

By using map + function, we can avoid using a large number of if-else statements, and perform better in terms of code simplicity, readability, maintainability and performance.


Organize content

Maps in C++ are very useful data structures for storing key-value pairs. Maps are the best way to store where we can directly lookup and access values ​​using keys with optimal time complexity.

However, did you know that you can also store functions as values ​​in C++ maps? That's right - a map can be used to store and quickly access a set of functions that need to be called at different times in the program. Let's examine the graph of the function.

Maps in C++ are very useful data structures for storing key-value pairs. Maps are the best way to store where we can directly lookup and access values ​​using keys with optimal time complexity.

However, did you know that you can also store functions as values ​​in C++ maps? That's right - a map can be used to store and quickly access a set of functions that need to be called at different times in the program. Let's examine the graph of the function.

grammar:

std::function<return_type(arg_type1, arg_type2, ...)> var_name;

In this code, return_type is the return type of the function, arg_type1 , _ arg_type2 _ etc. is the type of the function parameter.

To create a function map, we first need to define the function signature to use. In this case, we want to store functions that take two long arguments and return a long value. We can use a function template in a function 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 add, subtract, divide and multiply are added to the map object map using the 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 use 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

There are several advantages to using mapped storage functions. It allows you to easily add or remove functions at runtime, and also allows you to easily associate a name with each function, which makes the code easier to understand and maintain. Let's understand it with a question.

Problem statement:

You've been given an array of strings called tokens that represent arithmetic expressions written in Reverse Polish Notation (RPN). Your task is to evaluate this expression and return the result as an integer. Each operand can be an integer or other RPN expression. When dividing two integers, the result will always be truncated to zero. You can assume that the input represents a valid RPN expression, and there will be no division by zero.

Let's check some test cases to find out.

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++ Program to implement
// map of functions
#include <bits/stdc++.h>
using namespace std;

// Define a type alias for a function that takes two longs
// and returns a long
using func = function<long(long, long)>;

// Create a map that maps strings to functions
map<string, func> mp{
    
    
	// Plus function from functools
	{
    
     "+", plus<long>() },
	// Minus function from functools
	{
    
     "-", minus<long>() },
	// Divides function from functools
	{
    
     "/", divides<long>() },
	// Multiplies function from functools
	{
    
     "*", multiplies<long>() }
};

// Function to evaluate a Reverse Polish Notation (RPN)
// expression
int evalRPN(vector<string>& A)
{
    
    
	// Create a stack to store the operands
	stack<long> s;

	// Iterate over the elements in the RPN expression
	for (auto i : A) {
    
    
		// If the element is not an operator, it is an
		// operand Convert it to an integer and push it onto
		// the stack
		if (!mp[i]) {
    
    
			s.push(stoi(i));
		}
		// If the element is an operator, pop the top two
		// operands from the stack Perform the operation and
		// push the result back onto the stack
		else {
    
    
			auto num1 = s.top();
			s.pop();
			auto num2 = s.top();
			s.pop();
			s.push(mp[i](num2, num1));
		}
	}

	// Return the result, which is the top element of the
	// stack
	return s.top();
}

int main()
{
    
    
	// Test the evalRPN function with an RPN expression
	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).

Guess you like

Origin blog.csdn.net/qq_29111047/article/details/132124565