Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <stack>
- #include <sstream>
- #include <cmath>
- #include <map>
- #include <functional>
- #include <stdexcept>
- using namespace std;
- double Calculate(const string& expression, const map<char, pair<unsigned, function<double(double, double)>>>& Operators) throw(invalid_argument)
- {
- stack<pair<double, signed char> > s;
- double Result=0, newNum;
- char oldOperator='\0', newOperator;
- istringstream iss(expression);
- while (true)
- {
- if (!(iss >> newNum))
- {
- iss.clear();
- if (iss.get()=='(')
- {
- s.push(make_pair(Result, -oldOperator));
- oldOperator='\0';
- continue;
- }
- else
- throw invalid_argument("非法字符或语法错误");
- }
- NEXT:
- if (!(iss >> newOperator))
- break;
- if (Operators.find(newOperator)==Operators.end())
- {
- if (newOperator==')')
- {
- Result=Operators.find(oldOperator)->second.second(Result, newNum);
- while (true)
- {
- if (s.empty())
- throw invalid_argument("括号不匹配,缺少左括号");
- if (s.top().second>0)
- {
- Result=Operators.find(s.top().second)->second.second(s.top().first, Result);
- s.pop();
- }
- else
- {
- oldOperator=-s.top().second;
- newNum=Result;
- Result=s.top().first;
- s.pop();
- goto NEXT;
- }
- }
- }
- else
- throw invalid_argument("非法运算符");
- }
- if (Operators.find(newOperator)->second.first>Operators.find(oldOperator)->second.first)
- {
- s.push(make_pair(Result, oldOperator));
- Result=newNum;
- }
- else
- {
- Result=Operators.find(oldOperator)->second.second(Result, newNum);
- if (Operators.find(newOperator)->second.first<Operators.find(oldOperator)->second.first)
- {
- while (!s.empty() && s.top().second>0 && Operators.find(newOperator)->second.first<Operators.find(s.top().second)->second.first)
- {
- Result=Operators.find(s.top().second)->second.second(s.top().first, Result);
- s.pop();
- }
- }
- }
- oldOperator=newOperator;
- }
- Result=Operators.find(oldOperator)->second.second(Result, newNum);
- while (!s.empty())
- {
- if (s.top().second<=0)
- throw invalid_argument("括号不匹配,缺少右括号");
- Result=Operators.find(s.top().second)->second.second(s.top().first, Result);
- s.pop();
- }
- return Result;
- }
- int main()
- {
- string s;
- map<char, pair<unsigned, function<double(double, double)>>> Operators;
- {
- Operators['+']=make_pair(1, plus<double>());
- Operators['-']=make_pair(1, minus<double>());
- Operators['*']=make_pair(2, multiplies<double>());
- Operators['/']=make_pair(2, divides<double>());
- Operators['^']=make_pair(3, [](double a, double b){return pow(a,b);});
- Operators['\0']=make_pair(~0, [](double, double b){return b;});
- }
- while (getline(cin, s) && s.empty());
- try
- {
- cout << Calculate(s, Operators) << endl;
- }
- catch (exception& e)
- {
- cerr << e.what() << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement