c++ - 在 C++ 中使用堆栈计算后缀表达式

标签 c++ stack postfix-notation

好的,我已经有了它的后缀表示法,我正在发送一个字符串变量,该变量将具有后缀表示法,例如: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++ 了,所以我有点生疏了。

最佳答案

如果您通过使用调试器单步执行来告诉我们是哪一行导致了错误,那会更容易一些。不过,我想我可能已经发现了错误。

在这段代码中

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) 而没有检查该元素是否存在。由于没有检查,您可能正在访问错误的内存位置。

关于c++ - 在 C++ 中使用堆栈计算后缀表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7883858/

相关文章:

c++ - 如何在 Xcode 上为 C++ 安装 vinecopulib 库?

c++ - 什么都不捕获的 lambda 可以访问全局变量吗?

matlab - 有没有办法将 MATLAB 工作区插入堆栈?

java - 使用java在中缀到后缀应用程序中获取错误输出

algorithm - 短路前缀 bool 表达式

c++ - 静态单例类对象的内存分配

c++ - 强制 C++ 编译器警告对象的所有堆栈实例

vector - 如何创建堆栈分配的类似矢量的容器?

使用堆栈和队列的 C++ 计算器

c++ - 在 OpenMP 缩减中使用多态类型