简体   繁体   English

转换函数以确定运算符优先级从C#到C ++

[英]Converting function to determine operator precedence from C# to C++

I need to convert some code from C# to C/C++. 我需要将一些代码从C#转换为C / C ++。 The effect of the function is to determine operator precedence for math evaluations. 该功能的作用是确定数学评估的运算符优先级。

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.");
}

I realize the numerous questions about strings in switch statements in C++, but that's not really what I'm asking. 我意识到C ++中switch语句中有关字符串的众多问题,但这并不是我真正要问的。 Obviously the switch(string) syntax is not legal in C++. 显然,switch(string)语法在C ++中不合法。 I don't want to use it. 我不想使用它。 I just need an efficient way to determine the precedence of the above operators short of initializing an entire map at the start of the program or large if-else chains (which is really just dancing around the swiitch statement). 我只需要一种有效的方法来确定上述运算符的优先级,而不必在程序或大型if-else链(实际上只是在swiitch语句周围跳舞)的开头初始化整个映射。

Any ideas how I can determine operator precedence? 有什么想法可以确定运算符优先级吗? Maybe a way to generate a unique code for each operator? 也许是一种为每个操作员生成唯一代码的方法?

As specified in this C# answer a switch with a string is compiled into a dictionary lookup or a if-else chain depending on the amount of cases. 如在此C#答案中所指定的,根据情况的不同,带有字符串的开关将编译为字典查找或if-else链。

The dictionary type in C++ is std::map , you could use a static dictionary in a scope and then search in it. C ++中的字典类型为std::map ,您可以在作用域中使用静态字典,然后在其中进行搜索。

So a straight equivalent, 1:1 conversion, would be something along those lines: 因此,按照这些原则,直接进行等效的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");
}

The advantage of using a statically stored dictionary instead of one with automatic storage duration here is that the container does not to be initialized (allocations!) every time you ask for OperatorPrecedence . 在这里使用静态存储的字典而不是具有自动存储持续时间的字典的优点是,每次您要求OperatorPrecedence时,都不会初始化容器(分配!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM