这是我在同一个实验室得到帮助的上一个帖子。我的堆栈是行为不端,至少可以说,当我添加一个项目到堆栈,以后打印出来时,它似乎没有添加正确。我总是打印出加'(+),如果我输入另一个操作数(*,/,+)无关紧要。
我正在使用堆栈将用户输入,中缀表达转换为后缀。它似乎工作得很好,除了在最后打印堆栈中的操作数。
#include <iostream>;
#include <vector>
using namespace std;
class DishWell{
public:
char ReturnFront(){
return Well.front();
}
void Push(char x){
Well.push_back(x);
}
void Pop(){
Well.pop_back();
}
bool IsEmpty(){
return Well.empty();
}
private:
vector<char> Well;
};
bool Precidence(char Input, char Stack){
int InputPrecidence,StackPrecidence;
switch (Input){
case '*':
InputPrecidence = 4;
break;
case '/':
InputPrecidence = 4;
break;
case '+':
InputPrecidence = 3;
break;
case '-':
InputPrecidence = 3;
break;
case '(':
InputPrecidence = 2;
break;
default:
InputPrecidence = 0;
}
switch (Stack){
case '*':
StackPrecidence = 4;
break;
case '/':
StackPrecidence = 4;
break;
case '+':
StackPrecidence = 3;
break;
case '-':
StackPrecidence = 3;
break;
case '(':
StackPrecidence = 2;
break;
default:
StackPrecidence = 0;
}
if(InputPrecidence>StackPrecidence) return true;
else return false;
}
int main(int argc, char** argv) {
DishWell DishTray;
char Input;
bool InputFlag;
InputFlag = true;
cout<<"Enter Input, invalid input will terminate"<<endl;
while(InputFlag){
cout<<"Input: ";
cin>>Input;
cout<<endl;
if((((Input>='a'&&Input<='z')||(Input>='A'&&Input<='Z'))||Input>='0'&&Input<='9')))//If Digit or Number
cout<<Input;
if((Input=='*'||Input=='/'||Input=='+'||Input=='-')){//if operand
if(DishTray.IsEmpty())
DishTray.Push(Input);
else if(Precidence(Input,DishTray.ReturnFront()))
DishTray.Push(Input);
else if(!Precidence(Input,DishTray.ReturnFront()))
cout<<"Output: "<<Input<<endl;
}
else if(!((((Input>='a'&&Input<='z')||(Input>='A'&&Input<='Z'))||(Input>='0'&&Input<='9')))||((Input=='*'||Input=='/'||Input=='+'||Input=='-')))//if not digit/numer or operand
InputFlag = false;
}
int counter = 0;
while(!DishTray.IsEmpty()){
counter++;
cout<<counter<<" Element "<<DishTray.ReturnFront()<<endl;
DishTray.Pop();
}
return 0;
谢谢Macaire Bell
答案 0 :(得分:1)
您的循环调用front()
,但随后调用pop_back()
。这将始终返回向量中的第一个元素,直到弹出所有元素,因为您永远不会删除前面的元素。你的ReturnFront()方法应该是:
char ReturnBack(){
return Well.back();
}
然后你的循环结束:
while(!DishTray.IsEmpty()){
counter++;
cout<<counter<<" Element "<<DishTray.ReturnBack()<<endl; // will return last element
DishTray.Pop(); // actually pop the element printed
}
答案 1 :(得分:1)
当您使用堆栈时,通常希望能够在堆栈顶部看到值。您的类只允许推送的第一个项目(即堆栈的底部)可见。你的ReturnFront()应该返回Well.back(),也许应该调用类似ReturnTop()的东西。
答案 2 :(得分:0)
你是否想要看到pop_back()返回的值,而不是像你现在那样丢弃它?