C++ Primer第五版习题9.52

来源:互联网 发布:淘宝外包公司 编辑:程序博客网 时间:2024/06/05 23:49

9.52 使用Stack处理括号化的表达式。

#include<iostream>#include<cstdlib>#include<vector>#include<string>#include<stack>using namespace std;// input string, return the value. // 涉及到各种变量到底该定义什么容器、类型好好思考void caculate(string &s) {    unsigned pos;    string v;    while ((pos = s.find_first_of("*/")) != string::npos) {        if (s[pos] == '*')            v = s[pos - 1] * s[pos + 1];        else            v = s[pos - 1] / s[pos + 1];        s = s.replace(pos - 1, 3, v);        }    while ((pos = s.find_first_of("+-")) != string::npos) {        if (s[pos]=='+')            v = s[pos - 1] + s[pos + 1];        else            v = s[pos - 1] - s[pos + 1];        s = s.replace(pos - 1, 3, v);        }}int main(){    string s;    cout << "Please enter a expression, better with(): " << endl;    cin >> s;     //string s("2*(5-3)/2+5");    stack<char> c_stk;    vector<unsigned> zuo;    string bdian("+-*/)");    string temp;    string::iterator beg = s.begin(), cur = s.begin();    string::iterator a;    for (a = s.begin();a != s.end(); ++a){          if(bdian.find(*a)!=string::npos){            if( *(a-1)==')'){                c_stk.push(*a);                ++cur;                beg = cur;                continue;            }                string ss(beg, cur);            c_stk.push(stod(ss));            c_stk.push(*a);            beg = cur;            beg++;        }        if (*a == '(') {            beg = cur;            beg++;            c_stk.push(*a);            zuo.push_back(c_stk.size());         }        else{            if(*a==')'){                if(zuo.size()){                    c_stk.pop();                    while(c_stk.size()!=zuo.back()){                        temp.insert(temp.begin(), c_stk.top());                        c_stk.pop();                    }                    c_stk.pop();                    zuo.pop_back();                    caculate(temp);                    c_stk.push(temp[0]);                    temp.clear();                  }                else                    cerr << "ilegal input!" << endl;            }        }        ++cur;    }    if (beg != s.end()) {        string ss(beg, s.end());        c_stk.push(stod(ss));    }    while(c_stk.size()){        temp.insert(temp.begin(), c_stk.top());        c_stk.pop();    }    if (temp.find(bdian)) {        caculate(temp);        cout << temp[0]+0 << endl;   //输出时类型强制转换,char和数值    }    system("pause");    return 0;}

仍旧不是很尽如人意,对于容器的使用和类型的转换之类的真正实践起来就觉得很糟糕,但是好歹代码跑起来了= = 用IDE果然还是比较好查错= =

原创粉丝点击