简单用栈实现加减括号判优
#include<bits/stdc++.h>
#define rep(i, n) for(int i=0;i!=n;++i)
#define per(i, n) for(int i=n-1;i>=0;--i)
#define Rep(i, sta, n) for(int i=sta;i!=n;++i)
#define rep1(i, n) for(int i=1;i<=n;++i)
#define per1(i, n) for(int i=n;i>=1;--i)
#define Rep1(i, sta, n) for(int i=sta;i<=n;++i)
#define L rt<<1
#define R rt<<1|1
#define inf (0x3f3f3f3f)
#define llinf (1e18)
#define ALL(A) A.begin(),A.end()
#define SIZE(A) ((int)A.size())
#define MOD (1e9 + 7)
#define PII pair<int,int>
typedef long long i64;
using namespace std;
enum obj_type {LP,RP,ADD,SUB,VAL};
struct obj {
obj(obj_type type,double val = 0){t = type;v = val;}
obj_type t;
double v;
};
inline void skipws(string &exp,size_t &p)
{
p = exp.find_first_not_of(" ",p);
}//跳过表达式的空格
inline void new_val(stack<obj> &so,double v)
{
if( so.empty() || so.top().t == LP )
so.push(obj(VAL,v));//如果为空栈或左括号
else if(so.top().t == SUB || so.top().t == ADD){//为运算符
obj_type type = so.top().t;
so.pop();
double value = so.top().v;
so.pop();
if(type == ADD)
so.push(obj(VAL,v+value));
else
so.push(obj(VAL,value-v));
}else
throw invalid_argument("缺少运算符");
}
int main() {
stack<obj> so;
string exp;
size_t p = 0,q;
double v;
cout << "请输入表达式:" << endl;
getline(cin,exp);
while(p < exp.size()){
skipws(exp,p);
if(exp[p] == '('){//左括号直接压栈
so.push(obj(LP));
++p;//处理下一个字符
}else if (exp[p] == '+' || exp[p] == '-'){
if(so.empty() || so.top().t != VAL )//空栈或不为数值
throw invalid_argument("缺少运算数");
if(exp[p] == '+')
so.push(obj(ADD));
else
so.push(obj(SUB));
++p;
}else if(exp[p] == ')'){
++p;
if(so.empty())
throw invalid_argument("未匹配右括号");
if(so.top().t == LP)
throw invalid_argument("空括号");
if(so.top().t == VAL){
v = so.top().v;
so.pop();
if(so.empty() || so.top().t != LP)
throw invalid_argument("不存在匹配右括号");
so.pop();//去掉左括号
new_val(so,v);//与表达式之前的相加减
}else
throw invalid_argument("缺少运算数");
}else{//数值
v = stod(exp.substr(p),&q);
p += q;
new_val(so,v);
}
}
if(so.size() != 1 || so.top().t != VAL)
throw invalid_argument("非法表达式");
cout << so.top().v << endl;
return 0;
}
不怕万人阻挡,只怕自己投降。
posted on 2020-06-30 17:07 chengyulala 阅读(189) 评论(0) 编辑 收藏 举报