AcWing 3302. 表达式求值
原题链接
简单
作者:
dsyami
,
2021-06-02 19:15:01
,
所有人可见
,
阅读 296
一个奇妙的段错误
#include <iostream>
#include <unordered_map>
#include <stack>
#include <algorithm>
using namespace std;
unordered_map<char, int> pr {{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
stack<int> num;
stack<char> op;
void eval()
{
int a, b, x;
char c;
b = num.top(); num.pop();
a = num.top(); num.pop();
c = op.top(); op.pop();
if(c == '+') x = a + b;
else if(c == '-') x = a- b;
else if(c == '*') x = a * b;
else x = a / b;
num.push(x);
}
int main()
{
string str;
cin >> str;
for (int i = 0; i < str.size(); i ++ )
{
if (isdigit(str[i]))
{
int j = i, x = 0;
while (isdigit(str[j]) && j < str.size())
x = x * 10 + str[j ++ ] - '0';
num.push(x);
i = j - 1;
}
else if (str[i] == '(') op.push(str[i]);
else if (str[i] == ')')
{
while (op.top() != '(') eval();
op.pop();
}
else
{
//错误类型:当栈为空时,调用top()会导致段错误
//while (pr[op.top()] >= pr[str[i]] && op.size()) eval();
while (op.size() && pr[op.top()] >= pr[str[i]]) eval();
op.push(str[i]);
}
}
while(op.size()) eval();
cout << num.top() << endl;
return 0;
}