Использование стеков в C ++ для оценки выражения Postfix - PullRequest
0 голосов
/ 25 октября 2011

Хорошо, у меня уже есть запись в постфиксной нотации, и я посылаю строковую переменную, которая будет иметь постфиксную нотацию, например: 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 not defrencable»

Любая помощь, которую я могу получить по этой ошибке, будет очень признательна. Кстати, я не использовал C ++ в течение нескольких лет, поэтому я немного заржавел.

1 Ответ

1 голос
/ 25 октября 2011

Было бы проще, если бы вы сказали нам, какая строка вызвала ошибку, пройдя через отладчик.Однако, я думаю, что я, возможно, заметил ошибку.

В этом блоке кода

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), даже не проверяя, существует ли этот элемент.Поскольку проверки нет, возможно, вы обращаетесь к неверным ячейкам памяти.

...