在C ++中使用Stacks来评估Postfix表达式

时间:2011-10-25 01:51:02

标签: c++ stack postfix-notation

好的,我已经在postfix表示法中使用了它,并且我发送了一个字符串变量,它将具有后缀表示法,例如:5 15 2 * + 这是我的代码:

int evaluatePostFix(string postfix_expression){
//Create a new stack
stack<int> theStack;
//Loops while the postfix expression string still contains values
while(postfix_expression.length()>=1){
    //Loops on a number an whitespace
    while(isdigit(postfix_expression.at(0)) || isspace(postfix_expression.at(0))){
        //Holds a number that is above two digits to be added to the stack
        string completeNum;
        if(isdigit(postfix_expression.at(0))){ 
            //Add the digit so it can become a full number if needed
            completeNum+=postfix_expression.at(1);
        }
        else {
            //Holds the integer version of completeNum
            int intNum;
            //Make completeNum an int
            intNum=atoi(completeNum.c_str());
            //push the number onto the stack
            theStack.push(intNum);
        }
        //Check to see if it can be shortened
        if(postfix_expression.length()>=1){
            //Shorten the postfix expression
            postfix_expression=postfix_expression.substr(1);
        }
    }
    //An Operator has been found
    while(isOperator(postfix_expression.at(0))){
        int num1, num2;
        char op;
        //Grabs from the top of the stack
        num1=theStack.top();
        //Pops the value from the top of the stack - kinda stupid how it can return the value too
        theStack.pop();
        //Grabs the value from the top of the stack
        num2=theStack.top();
        //Pops the value from the top of the stack
        theStack.pop();
        //Grab the operation
        op=postfix_expression.at(0);
        //Shorten the postfix_expression
        postfix_expression=postfix_expression.substr(1);
        //Push result onto the stack
        theStack.push(Calculate(num1,num2, op));
    }
}
return theStack.top();

}

我得到的错误是“Deque iterator not deferencable”

我将非常感谢您对此错误的任何帮助。 顺便说一下,我在几年内没有使用过C ++,所以我有点生疏了。

1 个答案:

答案 0 :(得分:1)

如果通过调试器逐步告诉我们哪一行导致错误会更容易。但是,我想我可能已经发现了错误。

在这段代码中

if(isdigit(postfix_expression.at(0))){ 
    //Add the digit so it can become a full number if needed
    completeNum+=postfix_expression.at(1);
}

你要求postfix_expression.at(1)而不检查该元素是否存在。由于没有检查,您可能正在访问错误的内存位置。