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.

My question is if stack “needs to be provided the underlying container. By default it’s std::deque, but it can be std::vector or std::list too.”. My questions are:

  • Why don’t we directly use the vector? As vector seems faster than deque.
  • When should we use stack instead of vector?

In order to fully answer those questions, I’d like to do some online searching.

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.”

So based on this, we can do the following:

  • If we know the upper bound of the stack size, we can use vector as a stack and reserve enough space before using this “stack”
  • 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).

Thanks for reading and I hope this is helpful.


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