Each adaptor defines two constructors: the default constructor that creates an empty object, and a constructor that takes a container and initializes the adaptor by copying the given container. For example, assuming that deq
is a deque<int>
, we can use deq
to initialize a new stack
as follows:
stack<int> stk(deq); // copies elements from deq into stk
By default both stack
and queue
are implemented in terms of deque
, and a priority_queue
is implemented on a vector
. We can override the default container type by naming a sequential container as a second type argument when we create the adaptor:
// empty stack implemented on top of vector
stack<string, vector<string>> str_stk;
// str_stk2 is implemented on top of vector and initially holds a copy of svec
stack<string, vector<string>> str_stk2(svec);
There are constraints on which containers can be used for a given adaptor. All of the adaptors require the ability to add and remove elements. As a result, they cannot be built on an array
. Similarly, we cannot use forward_list
, because all of the adaptors require operations that add, remove, or access the last element in the container. A stack
requires only push_back, pop_back
, and back
operations, so we can use any of the remaining container types for a stack
. The queue
adaptor requires back, push_back, front
, and push_front
, so it can be built on a list
or deque
but not on a vector
. A priority_queue
requires random access in addition to the front, push_back
, and pop_back
operations; it can be built on a vector
or a deque
but not on a list
.