题目描述
表达式求值模板
可扩展修改优先级
C++ 代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include<string>
#include<stack>
#include <unordered_map>
using namespace std;
stack<int> num;
stack<char> op;
void eval(){
auto b = num.top();num.pop();
auto a = num.top();num.pop();
char c = op.top();op.pop();
int x = 0;
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()
{
unordered_map<char,int> pro = {{'+',1},{'-',1},{'*',2},{'/',2}};//添加扩展符号优先级
string str;
cin >> str;
for (int i = 0; i < str.size(); i ++ ){
if(isdigit(str[i])){
int x = 0,j = i;
while(j < str.size() && isdigit(str[j]))
x = x*10 + str[j ++] - '0';
i = j-1;
num.push(x);
}
else if(str[i] == '(')op.push(str[i]);
else if(str[i] == ')'){
//不用担心op栈里的符号优先级,因为下一个else条件已经处理
while(op.top() != '(') eval();
op.pop();//弹出')'
}
else{
while(op.size() && pro[op.top()] >= pro[str[i]])eval();
op.push(str[i]);
}
}
while(op.size())eval();
cout << num.top() ;
return 0;
}