Containers in Practice
Stack Undo
A stack keeps the most recent item on top, which is the same access pattern used by simple undo histories.
Stack Undo
stack_undo.cpp
#include <iostream>
#include <stack>
#include <string>
int main() {
std::string latest = ;
std::stack<std::string> undo;
undo.push("open");
undo.push(latest);
std::string next = undo.top();
undo.pop();
int remaining = static_cast<int>(undo.size());
std::cout << "next=" << next << std::endl;
std::cout << "remaining=" << remaining << std::endl;
return 0;
}
#include <iostream>
#include <stack>
#include <string>
int main() {
std::string latest = ;
std::stack<std::string> undo;
undo.push("open");
undo.push(latest);
std::string next = undo.top();
undo.pop();
int remaining = static_cast<int>(undo.size());
std::cout << "next=" << next << std::endl;
std::cout << "remaining=" << remaining << std::endl;
return 0;
}
#include <iostream>
#include <stack>
#include <string>
int main() {
std::string latest = ;
std::stack<std::string> undo;
undo.push("open");
undo.push(latest);
std::string next = undo.top();
undo.pop();
int remaining = static_cast<int>(undo.size());
std::cout << "next=" << next << std::endl;
std::cout << "remaining=" << remaining << std::endl;
return 0;
}
stack
A `std::stack` exposes only the top item and follows last-in, first-out order.
undo
Undo histories use the newest action first, so a stack is a natural model.