如何将运算符与优先级值相关联?

How to associate an operator with a priority value?

我想实施 Reverse Polish notation。为此,我必须实现一个 table 来存储运算符的优先级,例如:

operator priority
( 0
+, - 1
*, / 2

我该怎么做?

由于您拥有在编译时已知的固定数量的键值对,因此您不需要 std::unordered_map 的动态特性和开销。您可以使用一个简单的 switch 语句,它是静态的并且不易出错:

int get_priority(char const op) {
  switch (op) {
    case '(':
      return 0;
    case '+':
    case '-':
      return 1;
    case '*':
    case '/':
      return 2;
    default:
      return -1; // handle the error
  }
}