C++ table-driven approach instead of if-else

Using dozens of if-else codes in succession is not efficient and the key points are tired. Remember to change to table-driven method.

#include <iostream>
#include <unordered_map>
#include <functional>

using namespace std;

void handleCondition1()
{
    
    
  // 处理条件 1 的代码
  std::cout << "Handling condition 1." << std::endl;
}

void handleCondition2()
{
    
    
  // 处理条件 2 的代码
  std::cout << "Handling condition 2." << std::endl;
}

void handleCondition3()
{
    
    
  // 处理条件 3 的代码
  std::cout << "Handling condition 3." << std::endl;
}

int main()
{
    
    
  std::unordered_map<std::string, std::function<void()>> conditionTable;

  // 将条件和相应的处理函数添加到映射表中
  conditionTable["condition1"] = handleCondition1;
  conditionTable["condition2"] = handleCondition2;
  conditionTable["condition3"] = handleCondition3;

  std::string condition = "condition2"; // 假设条件为 "condition2"

  // 根据给定的条件查找并调用相应的处理函数
  if (conditionTable.find(condition) != conditionTable.end())
  {
    
    
	conditionTable[condition](); // 调用相应的处理函数
  }
  else
  {
    
    
	// 如果条件不在映射表中的处理代码
	std::cout << "No matching handler for condition:"<< condition.c_str() << std::endl;
  }

  return 0;
}

In the above example, we used std::unordered_map to create a mapping table between conditions and handler functions. The type of the key is std::string, and the type of the value is std::function<void()>, which is a wrapper of a callable object, corresponding to a function with no parameters and a return type of void.

I added the conditions as keys and the corresponding handler functions as values ​​to the mapping table. Then, we determine whether the given condition exists by looking up the mapping table and call the corresponding processing function. If the condition is not in the mapping table, the corresponding processing code is executed.

Note that this example only demonstrates the implementation of a basic table-driven approach. Depending on your actual needs, you may need to implement appropriate error handling or a more complex design of the table-driven approach.


I recommend a Lingsheng Academy project class. I personally think the teacher taught it well. I would like to share it with you:
Lingsheng Platinum Learning Card (including infrastructure/high-performance storage/golang cloud native/audio and video/Linux kernel)
https://xxetb.xet .tech/s/VsFMs

Guess you like

Origin blog.csdn.net/qq_40135848/article/details/132671041