fork download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <iterator>
  4.  
  5. #include <vector>
  6. #include <string>
  7. #include <stack>
  8. #include <map>
  9. #include <functional>
  10.  
  11. using namespace std;
  12.  
  13. int compute(int a, int b, string op)
  14. {
  15. static map<string,function<int(int,int)> > operations;
  16. operations["+"] = plus<int>();
  17. operations["-"] = minus<int>();
  18. operations["*"] = multiplies<int>();
  19. operations["/"] = divides<int>();
  20.  
  21. return operations[op](b,a);
  22. }
  23.  
  24. int evalRPN(vector<string>& tokens)
  25. {
  26. int n = tokens.size();
  27. if (n == 0)
  28. return 0;
  29. stack<int> S;
  30. int a, b;
  31. for (int i = 0; i < n; i++)
  32. {
  33. string operators = "+-*/";
  34. string tmp = tokens[i];
  35. if (operators.find(tmp) != string::npos) // <== [1]
  36. {
  37. a = S.top(); S.pop();
  38. b = S.top(); S.pop();
  39. S.push(compute(a, b, tmp));
  40. }
  41. else
  42. {
  43. S.push(stoi(tmp));
  44. }
  45. }
  46. return S.top();
  47. }
  48.  
  49. int main() {
  50. vector<string> input;
  51. string tmp;
  52. getline(cin,tmp);
  53. istringstream istst(tmp);
  54.  
  55. copy(istream_iterator<string>(istst),
  56. istream_iterator<string>(),
  57. back_inserter(input));
  58.  
  59. cout << evalRPN(input);
  60. return 0;
  61. }
Success #stdin #stdout 0s 3432KB
stdin
33 9 - 5 3 + /
stdout
3