Question 5
Back to Exercise
Implement editor commands (Insert, Delete) as classes with execute and undo, stored as unique_ptr<Command> on undo and redo stacks; run a few edits, undos and redos.
Solution
#include <iostream>
#include <memory>
#include <stack>
#include <string>
struct Command {
virtual void execute(std::string& doc) = 0;
virtual void undo(std::string& doc) = 0;
virtual ~Command() = default;
};
struct Insert : Command {
std::size_t pos; std::string text;
Insert(std::size_t p, std::string t) : pos(p), text(std::move(t)) {}
void execute(std::string& d) override { d.insert(pos, text); }
void undo(std::string& d) override { d.erase(pos, text.size()); }
};
struct Delete : Command {
std::size_t pos, len; std::string removed;
Delete(std::size_t p, std::size_t l) : pos(p), len(l) {}
void execute(std::string& d) override { removed = d.substr(pos, len); d.erase(pos, len); }
void undo(std::string& d) override { d.insert(pos, removed); }
};
class Editor {
std::string doc_;
std::stack<std::unique_ptr<Command>> undo_, redo_;
public:
void run(std::unique_ptr<Command> c) { c->execute(doc_); undo_.push(std::move(c)); redo_ = {}; }
void undo() { if (undo_.empty()) return; undo_.top()->undo(doc_); redo_.push(std::move(undo_.top())); undo_.pop(); }
void redo() { if (redo_.empty()) return; redo_.top()->execute(doc_); undo_.push(std::move(redo_.top())); redo_.pop(); }
void show() const { std::cout << '[' << doc_ << "]\n"; }
};
int main() {
Editor e;
e.run(std::make_unique<Insert>(0, "Hello World"));
e.run(std::make_unique<Insert>(5, ","));
e.run(std::make_unique<Delete>(6, 6));
e.show();
e.undo(); e.show();
e.undo(); e.show();
e.redo(); e.show();
return 0;
}
[Hello,] [Hello, World] [Hello World] [Hello, World]
Commands move between the stacks – ownership is always clear and every command is freed exactly once. A new command clears the redo stack.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!