I wrote "Stop Using Arrays for Everything" and someone in the comments said: "Cool, now solve Advent of Code 2022 Day 5 your way." Challenge accepted.
The problem
Day 5 of AoC 2022: you have 9 stacks of crates. The input gives you the initial stacks, then a list of moves like "move 3 from stack 1 to stack 2". Move crates one at a time, maintaining order.
Here's what a beginner (past me) might write:
char stacks[9][100]; // fixed size, wasted space
int tops[9] = {0}; // manually track height for each stack
// Push a crate
stacks[from][tops[from]++] = 'A'; // off-by-one nightmare
You're managing two parallel arrays and a bunch of indices. It works but it's messy, rigid, and the code doesn't match the problem description at all.
The right tool exists
The problem literally calls them "stacks." C++ has std::stack. Use it.
#include <stack>
#include <vector>
vector<stack<char>> stacks(9);
// Push a crate
stacks[from].push('A');
// Pop a crate
char c = stacks[from].top();
stacks[from].pop();
No manual tops[] array. No fixed capacity. push() and pop() are exactly the words the problem statement uses. The code reads like English.
The full move logic
for (int i = 0; i < count; i++) {
stacks[to].push(stacks[from].top());
stacks[from].pop();
}
Three lines. If you wrote this with raw arrays, it would be twice as long and you'd spend half your time debugging an index.
Why this matters
The Advent of Code commenter was right — it's the perfect demo. When the problem says "stack," and your language has a stack class, the default should be to use it, not to reinvent it with arrays "because I know arrays."
Picking the right container isn't about being fancy. It's about writing code that you can look at two weeks later and still understand instantly.
My GitHub: https://github.com/Cn-Alanwu
Top comments (6)
See my new article,bro.
OK,I will read it in my free time.But I'm busy now.