fork download
  1. #include <list>
  2. #include <vector>
  3. #include <map>
  4. #include <functional>
  5. #include <iostream>
  6. #include <algorithm>
  7. #include <initializer_list>
  8.  
  9. class program {
  10. typedef std::list <int> args_t;
  11. typedef std::function<int(int,int)> op_t;
  12. typedef std::vector <op_t> code_t;
  13.  
  14. args_t args;
  15. code_t code;
  16.  
  17. public:
  18.  
  19. void compile (const std::string& expr) {
  20. static std::map <char, op_t> op_map = {
  21. {'+', std::plus<int>() }
  22. ,{'-', std::minus<int>() }
  23. };
  24.  
  25. for (auto c: expr) {
  26. isdigit(c) ?
  27. args.push_back (c-'0')
  28. : code.push_back (op_map[c]);
  29. }
  30. }
  31.  
  32. int next_arg () {
  33. int arg = *args.begin (); args.pop_front();
  34. return arg;
  35. }
  36.  
  37. int run () {
  38. for (auto op: code) {
  39. int lhs = next_arg();
  40. int rhs = next_arg();
  41. args.push_front (op (lhs, rhs));
  42. }
  43. return next_arg();
  44. }
  45. };
  46.  
  47. int main()
  48. {
  49.  
  50. program p;
  51. p.compile ("7+3-2+5");
  52. int result = p.run ();
  53. std::cout << result; // 13
  54. }
  55.  
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
13