我需要将一些代码从C#转换为C / C ++。该功能的作用是确定数学评估的运算符优先级。
private static int OperatorPrecedence(string strOp)
{
switch (strOp)
{
case "*":
case "/":
case "%": return 0;
case "+":
case "-": return 1;
case ">>":
case "<<": return 2;
case "<":
case "<=":
case ">":
case ">=": return 3;
case "==":
case "=":
case "!=": return 4;
case "&": return 5;
case "^": return 6;
case "|": return 7;
case "&&": return 8;
case "||": return 9;
}
throw new ArgumentException("Operator " + strOp + "not defined.");
}
我意识到有关C ++中switch语句中的字符串的众多问题,但这并不是我真正要问的。显然,switch(string)语法在C ++中是不合法的。我不想使用它。我只需要一种有效的方法来确定上述运算符的优先级,而不必在程序或大型if-else链(实际上只是在swiitch语句周围跳舞)的开头初始化整个映射。
有什么想法可以确定运算符优先级吗?也许是一种为每个操作员生成唯一代码的方法?
如在此C#答案中所指定的,根据情况的不同,带有字符串的开关将编译为字典查找或if-else链。
C ++中的字典类型为std::map
,您可以在范围内使用静态字典,然后在其中进行搜索。
因此,按照这些原则,直接进行等效的1:1转换是:
int OperatorPrecedence(const std::string& strOp)
{
static std::map<std::string, int> lookup = { {"*", 1}, {"/", 1} /* add more */ };
auto it = lookup.find(strOp);
if(it != lookup.end())
return it->second;
else
throw std::invalid_argument(std::string("Operator ") + strOp + "not defined");
}
在这里使用静态存储的字典而不是具有自动存储持续时间的字典的优点是,不必在每次请求时都初始化容器(分配!)OperatorPrecedence
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句