使用栈实现中缀转后缀(C++/STL)运行报错-1073741510求助
中缀表达式转后缀表达式运行时错误(错误码-1073741510)分析与修复
你的代码编译通过但运行崩溃,错误码-1073741510对应Windows平台的内存访问违规,核心问题是栈为空时调用了st.top()。比如处理第一个运算符+时,栈还没有元素,此时访问st.top()会触发未定义行为,直接导致程序崩溃。
修复要点
- 栈空判断:在比较运算符优先级前,必须先检查栈是否为空。栈空时直接将当前运算符压入栈,无需比较优先级。
- 优先级相等处理:原代码只处理了当前运算符优先级高于栈顶的情况,对于优先级相等的运算符(如连续的
+或-),需要先弹出栈顶运算符到后缀表达式,再压入当前运算符。 - 循环条件优化:用
i < infix.size()替代infix[i] != '\0',更符合C++字符串的遍历规范。
修复后的完整代码
#include<iostream> #include<stack> #include<string> using namespace std; int isOperator(char ch) { return (ch == '+' || ch == '-' || ch == '*' || ch == '/') ? 1 : 0; } int precedence(char ch) { if(ch == '*' || ch == '/') return 3; else if(ch == '+' || ch == '-') return 2; else return 0; } string infixtopostfix(string infix) { stack<char> st; int i = 0; string postfix; while(i < infix.size()) { if(!isOperator(infix[i])) { postfix.push_back(infix[i]); i++; } else { // 栈空或当前运算符优先级高于栈顶,直接压栈 if(st.empty() || precedence(infix[i]) > precedence(st.top())) { st.push(infix[i]); i++; } else { // 优先级小于等于栈顶,弹出栈顶到后缀表达式 postfix.push_back(st.top()); st.pop(); } } } // 弹出栈中剩余的运算符 while(!st.empty()) { postfix.push_back(st.top()); st.pop(); } return postfix; } int main() { string infix = "a+b"; cout << "Postfix-->" << infixtopostfix(infix) << endl; return 0; }
测试结果
运行修复后的代码,输入a+b会输出ab+,符合预期。
内容的提问来源于stack exchange,提问作者Munim Ahmed
相关产品推荐
相关产品推荐

