-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathundo_redo.cpp
More file actions
85 lines (73 loc) · 1.62 KB
/
undo_redo.cpp
File metadata and controls
85 lines (73 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>
#include <memory>
#include <string>
#include <vector>
using namespace std;
class Memento {
int balance;
public:
explicit Memento(int balance) : balance(balance) {}
friend class BankAccount;
};
// supports undo/redo
class BankAccount {
int balance = 0;
// save every snapshot commit
vector<shared_ptr<Memento>> changes;
size_t current;
public:
explicit BankAccount(const int balance) : balance(balance) {
changes.emplace_back(make_shared<Memento>(balance));
current = 0;
}
shared_ptr<Memento> deposit(int amount) {
balance += amount;
auto m = make_shared<Memento>(balance);
changes.push_back(m);
++current;
return m;
}
void restore(const shared_ptr<Memento> &m) {
if (m) {
balance = m->balance;
changes.push_back(m);
current = changes.size() - 1;
}
}
shared_ptr<Memento> undo() {
if (current > 0) {
--current;
auto m = changes[current];
balance = m->balance;
return m;
}
return {};
}
shared_ptr<Memento> redo() {
if (current + 1 < changes.size()) {
++current;
auto m = changes[current];
balance = m->balance;
return m;
}
return {};
}
friend ostream &operator<<(ostream &os, const BankAccount &obj) {
return os << "balance: " << obj.balance;
}
};
int main() {
BankAccount ba{100};
ba.deposit(50);
ba.deposit(25); // 125
cout << ba << "\n";
ba.undo();
cout << "Undo 1: " << ba << "\n";
ba.undo();
cout << "Undo 2: " << ba << "\n";
ba.redo();
cout << "Redo 2: " << ba << "\n";
ba.undo();
cout << "Undo 3: " << ba << "\n";
return 0;
}