后缀表示法的插图不尊重第二组括号
Infix to Postfix notation not respecting second set of parentheses
难以获得正确的结果infix :( a b)/(c-d)后缀:ab cd-/
我继续获得后缀:ab c/d -
我确实知道问题来自于它在推动之前无法从堆栈中弹出最后一个操作员的问题"。我做错了什么?还有其他方法可以解决这个问题吗?
#include <iostream>
#include <stack>
#include <sstream>
#include <string>
using namespace std;
int precedence(char x) {
int op;
if (x == '(' || x==')')
op = 1;
else if (x == '^')
op = 2;
else if (x == '*')
op = 3;
else if ( x == '/')
op = 4;
else if (x == '+')
op = 5;
else if (x == '-')
op = 6;
return op;
}
int main()
{
string getInfix;
cout << "Infix: ";
getline(cin, getInfix);
stack<char> opStack;
stringstream showInfix;
for (unsigned i = 0; i < getInfix.length(); i++)
{
if (getInfix[i] == '+' || getInfix[i] == '-' || getInfix[i] == '*' || getInfix[i] == '/' || getInfix[i] == '^')
{
while (!opStack.empty() && precedence(opStack.top() <= precedence(getInfix[i]))
{
showInfix << opStack.top();
opStack.pop();
}
opStack.push(getInfix[i]);
}
else if (getInfix[i] == '(')
{
opStack.push(getInfix[i]);
opStack.pop();
if (getInfix[i]=='(' && !opStack.empty())
{
opStack.push(getInfix[i]);
opStack.pop();
}
}
else if (getInfix [i]==')')
{
showInfix << opStack.top();
opStack.pop();
}
else
{
showInfix << getInfix[i];
}
}
while (!opStack.empty())
{
showInfix << opStack.top();
opStack.pop();
}
cout << "Postfix: "<<""<<showInfix.str() << endl;
cin.ignore ( numeric_limits< streamsize >:: max(),'n');
return 0;
}
您没有设置op
const int precedence(const char x) noexcept(true) {
switch (x) {
case '(': case ')':
return 1;
case '^':
return 2;
case '*':
return 3;
case '/':
return 4;
case '+':
return 5;
case '-':
return 6;
}
return -1;
}
它返回-1,但我会让您弄清楚那部分。它没有回答这个问题。看到您可能正在阅读垃圾值后,我才停下来。
问题来自此行(!opStack.empty() && precedence(opStack.top() <=precedence(getInfix[i]))
您正在弹出您发现的最后一个操作员,而无需检查您是否在括号语句中。在将操作员添加到输出字符串之前,您需要考虑括号字符。
与您的问题无关,而是一些建议:
- 缩进您的代码,简化可见性并相信我,节省了您(和我们)的时间。
- 请勿
push
,然后为(
或)
字符pop
,就像忽略它们一样。 - 您在这条线上缺少
)
,我想这是一个复制/粘贴问题:while (!opStack.empty() && precedence(opStack.top() <=precedence(getInfix[i]))
- 您确实意识到自己测试了
(
和)
的优先级,但是您从来没有使用该类型的字符来调用该方法?
相关文章:
- 将值从二维数组输出到文本文件
- 从父数组测试用例构造二叉树失败
- 在二维数组中查找最小值和最大值?
- 移动二维数组中的字符
- 如何将升压数组表示为类型的指针?
- 如何就地反转由数组表示的排列
- 从文本文件读取到表示一个月的二维数组中
- 如何在指针表示法和数组表示法中循环遍历二维数组
- C++:如何解释图像的字节数组表示
- C/C++ int[] vs int*(指针与数组表示法).有什么区别
- C++ 一种方法,该方法将十进制值作为用布尔数组表示的二进制的整数返回
- 将表示二维数组的 std::vector<std::vector <double> >转换为 cv::Mat
- 具有多维数组表示法的指针算术
- C++指针与数组表示法
- 在函数声明中,传递固定大小的数组表示什么
- 如何在 CUDA 中从稀疏数组表示形式变为密集数组表示形式
- 使用Cilk数组表示法和STL向量
- 尝试在此测试分数程序上使用指针表示法而不是数组表示法,但我被困住了
- 最小堆通过二叉树的数组表示;MoveDown函数无限循环
- 将二维数组赋值表示为指针数学