在c++stl中使用堆栈时出现分段错误

  • 本文关键字:分段 错误 堆栈 c++stl c++
  • 更新时间 :
  • 英文 :


我试图写这段代码来将中缀表达式转换为后缀表达式,但我遇到了一些值的分段错误。代码为:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stack>
#include <bits/stdc++.h> 
using namespace std;
int prec(char ch){
if(ch=='^')
return 3;
else if(ch=='*' || ch=='/')
return 2;
else if(ch=='+' || ch=='-')
return 1;
else 
return 0;
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */   
stack <char> st;
string s;
cin>>s;
for(int i=0;i<21;i++){
if((s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z'))
cout<<s[i];
else{
if( st.empty())
st.push(s[i]);
else  if( s[i]=='(' || prec (s[i])> prec(st.top()))
st.push(s[i]);
else if( s[i]==')'){
while(st.top()!='(')
{cout<<st.top(); st.pop();}
st.pop();
}
else{
while(prec(st.top())>=prec(s[i]))
{
cout<<st.top(); st.pop();
}
}
}
}
return 0;
}

对于较小的表达式,它给出了答案,但对于像a+b*(c^d-e(^(f+g*h(-i这样的表达式,则给出了分段错误。

首先,迭代应该只在字符串中。

这意味着

for(int i=0;i<21;i++){

应该是

for(int i=0;i<s.size();i++){

其次,您忘记检查循环中堆栈是否为空。

这意味着

while(prec(st.top())>=prec(s[i]))

应该是

while(!st.empty() && prec(st.top())>=prec(s[i]))

最新更新