字符串转化为数学表达式并求值(后缀表达式)

来源:互联网 发布:网络策划培训 编辑:程序博客网 时间:2024/04/29 19:23

主要用到后缀表达式和利用后缀表达式求值。

#include<iostream>#include<string>#include<cmath>#include<stack>#include<map>#include<vector>using namespace std;class Convert{public:Convert(string tot) :test(tot) {};void init() {pri["("] = 0;pri[")"] = 1;pri["*"] = pri["/"] = 2;pri["+"] = pri["-"] = 3;}int tomath() {int len = test.size();int i;init();string tem;string last="a";for (i = 0;i < len;i++) {if (test[i] <= '9'&&test[i] >= '0')tem += test[i];else {if(tem!="")postfix.push_back(tem);tem = "";last[0] = test[i];deal(last);}}if(tem!="")postfix.push_back(tem);while (!sign.empty()) {postfix.push_back(sign.top());sign.pop();}return calculate(postfix);}int calculate(vector<string> postfix) { // using stack stack<int> tem;int src1, src2;vector<string>::iterator iter;for (iter = postfix.begin();iter != postfix.end();iter++) {if (check(*iter))              // if it is a num ,push tem.push(stringtonum(*iter));else {src2 = tem.top();tem.pop();src1 = tem.top();tem.pop();tem.push(cal(src1, src2, *iter));}}return tem.top();}int cal(int src1, int src2, string tem) {              // + - * /if (tem == "*")return src1*src2;else if (tem == "/")return src1 / src2;else if (tem == "+")return src1 + src2;elsereturn src1 - src2;}int check(string tem) {                       //check if it is a numberif (tem == "*" || tem == "/" || tem == "+"||tem == "-")return 0;return 1;}void deal(string tem) {                         // sign to pushif (sign.empty())sign.push(tem);else {if (!pri[tem])                            //means (sign.push(tem);else if (pri[tem] == 1) {while (!sign.empty()&&sign.top() != "(") {postfix.push_back(sign.top());sign.pop();}sign.pop();}else if (pri[sign.top()] > pri[tem])sign.push(tem);else {while (!sign.empty()&&pri[sign.top()] <= pri[tem]&&pri[sign.top()]) {postfix.push_back(sign.top());sign.pop();}sign.push(tem);}}}int stringtonum(string source) {                    // conver string to numint num = 0;int len = source.size();int i;for (i = 0;i < len;i++) {num = num * 10;num = num + source[i] - '0';}return num;}private:string test;map<string, int> pri;stack<string> sign;vector<string> postfix;};int main(){string test = "16/4+2*(88/4/11-1)*(2+10)";Convert A(test);cout << A.tomath() << endl;system("Pause");return 0;}

0 0
原创粉丝点击