In the function vector in_to_post(vector infix) (the vector=(1 + 2) * 3 ^ 4 ) is being converted to an output vector which is of the form (Postfix: 1 2 + 3 4 ^ *) and i am getting an error saying invalid use of void expression . I have commented the lines where i am getting this error.
char get_optr(Token t) { // your code here return t.optr; } vector<Token> in_to_post(vector<Token> infix) { vector<Token> output; // your code here stack<Token>b; for(int i=0;i<infix.size();i++) { if(is_opnd(infix[i])) { output.push_back (infix[i]); } else if(get_optr(infix[i])=='(') { b.push(infix[i]); } else if(get_optr(infix[i])==')') { while(b.empty()==false) { //char i=get_optr(b.pop()); if(get_optr(b.pop())=='(') // I am getting error here { break; } else { output.push_back(b.pop()); //error } } } else if(is_opnd(infix[i])==false) { // char i=infix[i]; //char j=b.top(); if((priority(infix[i])>priority(b.top()))||get_optr(infix[i])=='('||get_optr(infix[i])==')') { b.push(infix[i]); } } } while(b.empty()==false) { output.push_back(b.pop()); //error } return output; }
Answer
The issue is that pop on a std::stack
simply pops the top element off the stack, but doesn’t return it. This function has a void
return type, and if you try to use it in a context that requires a value, you get an error
output.push_back(b.pop()); //error
Instead, you can use top to get top element of the std::stack
output.push_back(b.top()); // ok
Note that this will simply return a reference to the top element without popping it. You can call pop
after top
to pop it.