簡體   English   中英

在 C++ stl 中使用堆棧時出現分段錯誤?

[英]Segmentation error while using stacks in 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 這樣的表達式,它給出了分段錯誤。

首先,迭代應該只是在字符串中。

這意味着

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM