When to use stacks instead of a vector?

From what I understand stacks are just vectors which can only be operated on from one end. Vectors, on the other hand, are versatile dynamic arrays, which you can insert or delete things from the middle, add information to the front, the end, etcetera. on the other hand, a stack only operates on one end, the top.

Syntactically and implementation wise, they are not necessarily the same, but I don't think there is any operation a stack can perform with which a vector can not already do?

So with that in mind, is there ever any real reason to use a stack instead of a vector?
I asked a question similar to this when I was newer.

The answer pretty much is: The reason to use a stack over a vector is because the interface of a stack is simpler. You use a stack for a specific purpose. The less complexity your code has, the better. Less complexity means less room for error or bugs. Less complexity, and a reduced interface, lowers the chances of you or someone else maintaining your code to use that element in an improper or unintended way in the future.

But a stack also has limited use cases, due to this simplicity. It has its purpose for things like syntax parsing, undo capabilities, and what-not. If you need more functionality, use a different data structure.

_____________________________________

PS: In a way, it's analogous to asking "why use lists when you can use trees". After all, trees are just like lists except with the added functionality of being able to branch at each node. The answer to this is similar: By using a tree, you're making your code more complicated, and harder to follow. Unless you need the functionality provided by a tree, or having another good reason (like O(log n) lookups instead of O(n) lookups), don't use it.
Last edited on
Topic archived. No new replies allowed.