Question

I've been trying to implement shunting yard algorithm. The code gets an input from the user and after it is evaluated by another function (which is done already), it will be converted to postfix notation and then passed to be computed. The code below is just for the algorithm itself. ie is the vector of tokens made from user's input. The code makes sense to me but it doesn't compile, yet can't figure out where is not quite right.

  double eval_infix_expr(vector<Token> ie, map<string,double> sym_tab)
{
    vector<Token> postfix_expr;



static bool IsOperator(const string& token) {
  return token == "+" ||
         token == "-" ||
         token == "*" ||
         token == "/" ||
         token == "%";
}

static int PrecedenceOf(const string& token) {
  if (token == "+" || token == "-") return 0;
  if (token == "*" || token == "/" || token == "%") return 1;
  throw runtime_error("Unknown operator: " + token);
}




bool expectingOperator = false;


  for (size_t i = 0; i < ie.size(); ++i) {

    if (IsOperator(ie[i])) {

      if (!expectingOperator)
        throw runtime_error("Unexpected operator: " + ie[i]);



      while (!sym_tab.empty() && IsOperator(sym_tab.top()) &&
             PrecedenceOf(sym_tab.top()) >= PrecedenceOf(ie[i])) {
        postfix_expr.push_back(sym_tab.top()); sym_tab.pop();
      }


      sym_tab.push(ie[i]);

    expectingOperator = false;
    }


    else if (ie[i] == "(") {

      if (expectingOperator)
        throw runtime_error("Expected operator, found (.");
      sym_tab.push(ie[i]);
    }

    else if (ie[i] == ")") {


      if (!expectingOperator)
        throw runtime_error("Expected value, found ).");



      while (!sym_tab.empty() && sym_tab.top() != "(") {
        postfix_expr.push_back(sym_tab.top()); sym_tab.pop();
      }


      if (sym_tab.empty())
        throw runtime_error("Imbalanced parentheses.");


      sym_tab.pop();


      expectingOperator = true;
    }

    else {

      if (expectingOperator)
        throw runtime_error("Expecting operator, found " + ie[i]);


      postfix_expr.push_back(ie[i]);

 expectingOperator = true;
    }
  }


  if (!expectingOperator)
    throw runtime_error("Expected value, didn't find one.");


  while (!sym_tab.empty()) {
    if (sym_tab.top() == "(")
      throw runtime_error("Imbalanced parentheses.");
    postfix_expr.push_back(sym_tab.top()); sym_tab.pop();
  }
}


    postfix_Evaluator pe(postfix_expr);
    return pe.eval();

}

}

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top