Like the title asks Is there any time or space difference between a std::vector used as a stack and a std::stack ?
-
3std::stack is a container adapter that can be based on std::vector. So in fact there is no difference. – Vlad from Moscow Apr 28 '17 at 10:45
2 Answers
A std::stack
wraps another container. If the backing container of your stack is a std::vector
, then no, there is no difference.
The default backing container is however a std::deque
, which can have different storage and timing behaviour
See std::stack for details

- 11,313
- 33
- 58
No, there is no difference in complexity. std::vector
is a Container. std::stack
is an Adaptor of a container.
By default std::stack
uses std::deque
as the container it "adapts". But its actually a class-template that allows you to pass in the type of the underlying container you want it to use.
You can equally use a std::vector
as the underlying container:
template<typename T>
using MyVectorStack = std::stack<T, std::vector<T>>;
However,
In the case of std::stack
, the difference between using std::deque
vs std::vector
as the underlying container is primarily its memory allocation strategies.
When popping from a std::vector
, there's no chance that memory will be returned to the memory allocator unless if the vector is empty. When popping from a std::deque
, memory may be returned to the memory allocator if the "pop" frees a deque block.