我正在尝试实现一种算法,该算法采用 Token 类型的向量(Token 在另一个 .cpp 文件中创建)并将给定的中缀表达式转换为后缀表达式。
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 == "/"){return 1;}
throw runtime_error("Unkown operator:" + token);
}
double eval_infix_expr(vector<Token> ie, map<string,double> sym_tab)
{
vector<Token> postfix_expr;
stack <string> stack;
while(!ie.empty()){
for(size_t i = 0; i < ie.size(); ++i){
Token token = ie[i];
if(!(token.type == OPERATOR)){
postfix_expr.push_back(token);
}else if(token.type == OPERATOR){
while (!stack.empty() && isOperator(stack.top()) &&
PrecedenceOf(stack.top()) >= PrecedenceOf(token.value)){
//postfix_expr.push_back(stack.top()); stack.pop();
}
stack.push(token.value);
}
}
}
Postfix_Evaluator pe(postfix_expr);
return pe.eval();
}
被注释掉的行是目前程序中唯一给我带来困难的部分,我想知道如何正确地获取堆栈的顶部并将其插入向量中?