Reputation: 6088
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?
Upvotes: 0
Views: 154
Reputation: 10252
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
.
Upvotes: 1