标签:char return ops make map2 求值 include 表达式
#include <iostream> #include <cstring> #include <string> #include <cctype> #include <algorithm> #include <stack> #include <map> #include <sstream> using namespace std; //只作为一个参考 //约定表达式都是合法的,且在一行内输入,并没有空格 //约定运算符有 + - * /(整除) ( ) //约定操作数都是一位正整数,没有负号 //获得前后两个的优先级 //右// + - * / ( ) # //左// + > > < < < > > // - > > < < < > > // * > > > > < > > // / > > > > < > > // ( < < < < < = > // ) > > > > x > > // # < < < < < < = static const char map1[7][7]={ {'>','>','<','<','<','>','>'}, {'>','>','<','<','<','>','>'}, {'>','>','>','>','<','>','>'}, {'>','>','>','>','<','>','>'}, {'<','<','<','<','<','=','>'}, {'>','>','>','>','x','>','>'}, {'<','<','<','<','<','<','='}, }; static map<char,int> map2; void init_map(){ map2.insert(make_pair('+',0)); map2.insert(make_pair('-',1)); map2.insert(make_pair('*',2)); map2.insert(make_pair('/',3)); map2.insert(make_pair('(',4)); map2.insert(make_pair(')',5)); map2.insert(make_pair('#',6)); } char get(char before,char after){ return map1[map2[before]][map2[after]]; } //1 op 0 num string gettype(char c){ if(isdigit(c)) return "number"; else return "op"; } int calculate(int a,int b,char op){ switch (op) { case '+': return a+b; case '-': return a-b; case '*': return a*b; case '/': return a/b; } exit(-1); } int main(){ stack<char> ops; stack<int> s; string c; char t; init_map(); cin>>c; c=c+"#";//#作为分隔符 stringstream ss(c); ops.push('#'); ss>>t; while (1) { //输入、处理都完成 if(ops.top()=='#'&&t=='#') break; if(gettype(t)=="number") { s.push(t-'0'); ss>>t; } else{ switch (get(ops.top(),t)) { case '<': ops.push(t); ss>>t; break; case '>': int x1,x2; char _op; x1=s.top();s.pop(); x2=s.top();s.pop(); _op=ops.top();ops.pop(); //这里注意操作数的顺序,因为先进后出,所以x2在前面 s.push(calculate(x2,x1,_op)); break; case '=': ss>>t; ops.pop(); break; } } } cout<<s.top()<<endl; // cout<<get('+','-')<<endl; return 0; }
标签:char,return,ops,make,map2,求值,include,表达式 来源: https://www.cnblogs.com/MorrowWind/p/13056655.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。