简体   繁体   中英

Converting function to determine operator precedence from C# to C++

I need to convert some code from C# to 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. Obviously the switch(string) syntax is not legal in 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).

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.

The dictionary type in C++ is std::map , you could use a static dictionary in a scope and then search in it.

So a straight equivalent, 1:1 conversion, would be something along those lines:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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