I'm trying to implement an algorithm that takes a vector of type Token(Token is created in another .cpp file) and convert the infix expression given into a postfix expression.

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

}

The line which is commented out is the only part of the program at the moment which is giving me difficulty, I am wondering how do I properly take the top of a stack and insert it into a vector?

有帮助吗?

解决方案

The problem here is that the stack and vector contain different types. The stack contains string, while the vector contains Token. You will need to construct a Token from a string as in:

postfix_expr.push_back(Token(stack.top()));

Of course you will need the appropriate constructor implemented in Token.

Also you shouldn't name your stack the same as its data type. Name it something like tokenStack as to avoid conflicts in the variable name and type with the compiler.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top