#include <iostream> #include <functional> #include <map> #include <vector> using namespace std; using Action = function<void()>; struct UserAction { Action redo; Action undo; }; using Storage = map<double, double>; void print(const Storage & storage) { cout << "{ "; for (auto value:storage) cout << "{" << value.first << ", " << value.second << "}, "; cout << " }" << endl; } void addValue(Storage & storage, double time, double value) { storage.emplace(time, value); } void removeValue(Storage & storage, double time) { storage.erase(time); } void testUndoRedo() { cout << "initial storage:" << endl; Storage storage; addValue(storage, 5, 7); addValue(storage, 6, 8); print(storage); cout << "user actions:" << endl; vector<UserAction> actions; UserAction add_value{ bind(&addValue, ref(storage), 7, 9) , bind(&removeValue, ref(storage), 7) }; actions.push_back(add_value); (*actions.rbegin()).redo(); print(storage); UserAction add_other_value{ bind(&addValue, ref(storage), 6.5, 4) , bind(&removeValue, ref(storage), 6.5) }; actions.push_back(add_other_value); (*actions.rbegin()).redo(); print(storage); UserAction remove_value{ bind(&removeValue, ref(storage), 6) , bind(&addValue, ref(storage), 6, storage.at(6)) }; actions.push_back(remove_value); (*actions.rbegin()).redo(); print(storage); cout << "undo user actions:" << endl; for (auto i = actions.rbegin(); i != actions.rend(); ++i) { (*i).undo(); print(storage); } cout << "redo user actions:" << endl; for (auto i = actions.begin(); i != actions.end(); ++i) { (*i).redo(); print(storage); } } int main() { testUndoRedo(); return 0; }
Standard input is empty
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}, }