Advertisement
Guest User

Untitled

a guest
Jun 6th, 2014
1,223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. #include <iostream>
  2. #include <map>
  3. #include <stack>
  4. #include <functional>
  5. #include <utility>
  6. #include <stdlib.h>
  7.  
  8. using namespace std;
  9.  
  10. int main(int argc, char** argv) {
  11.   stack<double> s;  stack< pair<int, char> > ops;
  12.  
  13.   auto p = [&s, &ops] (function<double (double, double)>& f)
  14.     {double r=s.top();s.pop();r=f(s.top(),r);s.pop();s.push(r);ops.pop();};
  15.  
  16.   map< char, pair< int, function<double (double, double)> > > m =
  17.     {{'+', {1, [](double a, double b){return a+b;}}},{'-', {1, [](double a, double b){return a-b;}}},
  18.      {'*', {2, [](double a, double b){return a*b;}}},{'/', {2, [](double a, double b){return a/b;}}}};
  19.  
  20.   const int order = 2; int level = 0;
  21.   for (char* sp = argv[1];; ++sp) {
  22.     while (*sp == '(') {level += order; ++sp;}
  23.  
  24.     s.push(strtod(sp, &sp));
  25.  
  26.     while (*sp == ')') {level -= order; ++sp;}
  27.  
  28.     if (!*sp) {while(!ops.empty()) p(m[ops.top().second].second); break;}
  29.  
  30.     const int op =  m[*sp].first + level;
  31.     while (!ops.empty() && ops.top().first >= op) p(m[ops.top().second].second);
  32.  
  33.     ops.push(make_pair(op, *sp));
  34.   }
  35.  
  36.   cout << s.top() << endl;
  37.   return 0;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement