如何简化许多if else语句

问题描述 投票:0回答:2

我想简化这段代码,想让它更智能,大约有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}
}
}




c++ if-statement simplify design state-pattern
2个回答
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();
...

链接。http:/www.cplusplus.comreferencefunctionalbind, http:/www.cplusplus.comreferencefunctionalfunctionfunction, http:/www.cplusplus.comreferenceunordered_mapunordered_map


-2
投票

你可以试试嵌套的三元。

void spy::run(string num, SingleS single, MultipleS multipleS)
{

    (num=="1")?singleS.runS1:(num=="2")?singleS.runS2:(num=="3")?singleS.runS3:(num=="4")...;
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.