fork download
  1. #include <iostream>
  2. #include <functional>
  3. #include <map>
  4. #include <vector>
  5.  
  6. using namespace std;
  7.  
  8. using Action = function<void()>;
  9.  
  10. struct UserAction
  11. {
  12. Action redo;
  13. Action undo;
  14. };
  15.  
  16. using Storage = map<double, double>;
  17.  
  18. void print(const Storage & storage)
  19. {
  20. cout << "{ ";
  21. for (auto value:storage)
  22. cout << "{" << value.first << ", " << value.second << "}, ";
  23. cout << " }" << endl;
  24. }
  25.  
  26. void addValue(Storage & storage, double time, double value)
  27. {
  28. storage.emplace(time, value);
  29. }
  30.  
  31. void removeValue(Storage & storage, double time)
  32. {
  33. storage.erase(time);
  34. }
  35.  
  36. void testUndoRedo()
  37. {
  38. cout << "initial storage:" << endl;
  39. Storage storage;
  40.  
  41. addValue(storage, 5, 7);
  42. addValue(storage, 6, 8);
  43. print(storage);
  44.  
  45. cout << "user actions:" << endl;
  46. vector<UserAction> actions;
  47.  
  48. UserAction add_value{ bind(&addValue, ref(storage), 7, 9)
  49. , bind(&removeValue, ref(storage), 7) };
  50. actions.push_back(add_value);
  51. (*actions.rbegin()).redo();
  52. print(storage);
  53.  
  54. UserAction add_other_value{ bind(&addValue, ref(storage), 6.5, 4)
  55. , bind(&removeValue, ref(storage), 6.5) };
  56. actions.push_back(add_other_value);
  57. (*actions.rbegin()).redo();
  58. print(storage);
  59.  
  60. UserAction remove_value{ bind(&removeValue, ref(storage), 6)
  61. , bind(&addValue, ref(storage), 6, storage.at(6)) };
  62. actions.push_back(remove_value);
  63. (*actions.rbegin()).redo();
  64. print(storage);
  65.  
  66. cout << "undo user actions:" << endl;
  67. for (auto i = actions.rbegin(); i != actions.rend(); ++i)
  68. {
  69. (*i).undo();
  70. print(storage);
  71. }
  72.  
  73. cout << "redo user actions:" << endl;
  74. for (auto i = actions.begin(); i != actions.end(); ++i)
  75. {
  76. (*i).redo();
  77. print(storage);
  78. }
  79. }
  80.  
  81. int main()
  82. {
  83. testUndoRedo();
  84.  
  85. return 0;
  86. }
Success #stdin #stdout 0s 16072KB
stdin
Standard input is empty
stdout
initial storage:
{ {5, 7}, {6, 8},  }
user actions:
{ {5, 7}, {6, 8}, {7, 9},  }
{ {5, 7}, {6, 8}, {6.5, 4}, {7, 9},  }
{ {5, 7}, {6.5, 4}, {7, 9},  }
undo user actions:
{ {5, 7}, {6, 8}, {6.5, 4}, {7, 9},  }
{ {5, 7}, {6, 8}, {7, 9},  }
{ {5, 7}, {6, 8},  }
redo user actions:
{ {5, 7}, {6, 8}, {7, 9},  }
{ {5, 7}, {6, 8}, {6.5, 4}, {7, 9},  }
{ {5, 7}, {6.5, 4}, {7, 9},  }