I came across this:
It triggered me the question, how are stacks implemented in STL?
I am looking for a description similar to:
I came across this:
It triggered me the question, how are stacks implemented in STL?
I am looking for a description similar to:
stack
is an adapter which uses another container for the underlying storage, and links the functions push
, pop
, emplace
etc. to the relevant functions in the underlying container.
By default, std::stack
uses std::deque
as underlying container. But you can specify your own, e.g. std::stack<T, std::vector<T>> s;
.
For more details about this, see cppreference.
std::stack
has a template parameter Container
, which is required to be a container that can store elements of type T
(that is to say, the type of the elements of the stack). This container is required to have back()
, push_back()
and pop_back()
functions, and the standard containers vector
, deque
and list
all satisfy the requirements.
So, whichever container type the user specifies, the resulting instantiation of std::stack
is a class which:
Container<T>
(or something very similar if not literally a data member. I suppose it could probably be a private base class).push_back()
on the container whenever you call push()
on the stack.pop_back()
on the container whenever you call pop()
on the stack.Loosely speaking, std::stack<T>
is an object that wraps up an instance of std::deque<T>
, and hides most of deque
's functionality in order to present a simpler interface solely for use as a last-in-first-out (LIFO) queue. Similarly std::queue
presents a FIFO queue.