首页 > 解决方案 > 在c ++ stl中使用堆栈时出现分段错误?

问题描述

我试图编写此代码以将中缀表达式转换为后缀表达式,但我遇到了某些值的分段错误。代码是:

    #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^de)^(f+g*h)-i 这样的表达式,它给出了分段错误。

标签: c++

解决方案


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

这意味着

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]))

推荐阅读