c++ - 在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]))
推荐阅读
- flutter - 无法识别样式参数
- python - 在python中识别子和父组合组
- asp.net-core - 如何通过 DI 将经过身份验证的用户 ID 传递给 asp.net 核心中的类库项目?
- git - 无法重写分支:您有未暂存的更改
- php - 将 JSON 数据从视图中的 JavaScript 传递到 laravel 中的控制器
- python - 如何在没有 NumPy 的情况下将矩阵的行转换为 Python 中的列?
- java - 将命名参数传递给方法
- swift - (Q) 如何在 SwiftUI 中使用按钮动作
- php - 如何在codeigniter中更新多个值
- android - 从android中的服务类更改布局搜索栏