user14399919
user14399919

Reputation:

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?

Upvotes: 0

Views: 119

Answers (1)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29985

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

Upvotes: 2

Related Questions