Difference between a vector and a stack?

My questions

A discussion between the difference of a vector and a stack in C++ can be found here.

  • When should we use stack instead of vector?

What is stack?

From [1], it is pretty clear described about what is stack.

Why deque is the default container not the vector?

An explanation from here can answer this question.


Based on the previous section, we know that deque is preferred as “As the container grows, a reallocation for a vector requires copying all the elements into the new block of memory. Growing a deque allocates a new block and links it to the list of blocks — no copies are required.”

  • If we wanna use stack with an unknown upper bound of the stack size, we can either use stack (with deque as the default container) or we can use deque directly: stack is push and pop while deque is push_back and pop_back (slightly different in the API).


[1] https://www.cplusplus.com/reference/stack/stack/

Data Scientist/MLE/SWE @takemobi

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store