模板题表达式求值一遍过
作者:
jy9
,
2024-07-27 11:15:32
,
所有人可见
,
阅读 2
#include <iostream>
#include <unordered_map>
#include <stack>
using namespace std;
stack<int> num;
stack<char> op;
unordered_map<char, int> mp = {{'(', 0}, {'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
void eval(){
int b = num.top();
num.pop();
int a = num.top();
num.pop();
char x = op.top();
op.pop();
int ans;
if(x == '+') ans = a+b;
else if(x == '-') ans = a-b;
else if(x == '*') ans = a*b;
else if(x == '/') ans = a/b;
num.push(ans);
}
int main(){
string str;
cin >> str;
for (int i = 0; i < str.size(); i ++ ){
char t = str[i];
if(isdigit(t)){
int j = i;
int x = 0;
while(j < str.size() && isdigit(str[j])){
x = x * 10 + str[j] - '0';
j++;
}
i = j - 1;
num.push(x);
}else if(t == '(')op.push('(');
else if(t == ')'){
while(op.top() != '(') eval();
op.pop();
}else{
while(op.size() && mp[t] <= mp[op.top()]) eval();
op.push(t);
}
}
while(op.size()) eval();
cout << num.top();
return 0;
}