Search code examples
c++algorithmpostfix-notation

How to associate an operator with a priority value?


I want to implement Dijkstra's Shunting-yard algorithm for the Reverse Polish notation. In order to do that, I have to implement a table which stores priority for operators, as such:

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

How do I do that?


Solution

  • Since you have a fixed-number of key-value pairs that are known at compile time, you don't need the dynamic nature and overhead of std::unordered_map. You can use a simple switch statement, which is static and harder to get wrong:

    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
      }
    }