我试图实现一种算法,它需要一个类型为Token(令牌在另一个.cpp文件中创建)的向量,并将给定的中缀表达式转换为后缀表达式。将Stack.top()添加到Vector?
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();
}
其被注释掉是它给我困难的时刻程序的唯一部分的线,我想知道我怎么走好堆栈的顶部,并插入成矢量?
如何使用deque而不是stack? deque为您提供了一种获取和移除项目的方法。而且,我认为你必须将字符串类型转换为令牌类型。 –