0

我一直在尝试实现调车场算法。代码从用户那里得到一个输入,在它被另一个函数评估之后(这已经完成了),它将被转换为后缀符号,然后传递给计算。下面的代码仅适用于算法本身。ie 是由用户输入生成的标记向量。该代码对我来说很有意义,但无法编译,但无法弄清楚哪里不太正确。

  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();

}

}
4

0 回答 0