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

问题描述

我想实现 Reverse Polish notation。为了做到这一点,我必须实现一个存储运算符优先级的表,如下所示:

运算符 优先级
( 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
  }
}