如何简化许多 if else 语句

bcn*_*cng 0 c++ if-statement

我想简化这段代码并想让它更智能,大约有 80 个单S和多S。我考虑过状态设计模式的使用,但似乎不会更简单。任何人都可以帮助我解决以下问题:

void spy::run(string num, SingleS single, MultipleS multipleS)
{
if(num == "1")
{singleS.runS1}
else if(num == "2")
{singleS.runS2}
else if(num == "3")
{singleS.runS3}
else if(num == "4")
{singleS.runS4}
else if(num == "5")
{singleS.runS5}
else if(num == "6")
{singleS.runS6}
else if(num == "7")
{singleS.runS7}
else if(num == "8")
{singleS.runS8}
else if(num == "9")
{singleS.runS9}
else if(num == "10")
{multipleS.runS10}
else if(num == "11")
{multipleS.runS11}
else if(num == "12")
{multipleS.runS12}
else if(num == "13")
{multipleS.runS13}
}
}




Run Code Online (Sandbox Code Playgroud)

Ski*_*ent 5

您可以像这样使用 std::map 或 std::unordered_map

std::unordered_map<std::string, std::function<void(void)>> functionsMap = {
   {"1", std::bind(&SingleS::runS1, &singleS)},
   {"12", std::bind(&MultipleS::runS12, &multipleS)},
...
};

auto it = functionsMap.find(num);
if (it != functionsMap.end())
    it->second();
...
Run Code Online (Sandbox Code Playgroud)

链接:http://www.cplusplus.com/reference/functional/bind/ , http://www.cplusplus.com/reference/functional/function/function/ , http://www.cplusplus.com/reference/ unordered_map/unordered_map/