Container
adapters
n
The container
adapters are:
n
stacks
n
queues
n
priority queues
n
They are not containers but
subclasses that provide a limited subset of container operations
n
They are
implemented in terms of an underlying container
Stacks
n
A stack is a LIFO
(last in first out ) data structure
n
With the stack
container adapter there is no way to access any of a stack’s elements except
for the top element;
n
stack does not allow
iteration through its elements
n
This restriction
is the only reason stack exists, since you could implement a stack with a
sequence container, using back( ), push_back(
), and pop_back( )
Implementing
a stack
n
The default stack
is implemented using a deque, but this can be overridden
n
template
<class T, class Containter = deque<T> >
class stack;
n
Member function
of stack
push( ), pop( ), top( ), empty( ), size( )
n
The stack
implementation maps these operations to function calls to the container that is
used internally
n
push( ) maps to push_back( )
n
top( ) maps to back( )
n
pop( ) maps to pop_back( )
n You must include the header file <stack>
top( ) & pop( )
n
pop( ) does not return a
value because it is inefficient to do so.
n
If you want to
process the top of the stack after it is popped you must call top( ) before
n
This is true for
all three container adapters, queues and priority queues as well a stacks
Queues
n
A queue is a FIFO
first in first out data structure
n
By default uses a
deque as the underlying container
n
There is no way
to access any of a queue’s elements except for the ones at the front and back;
it has no iterators
n
The only reason to
use the container adaptor queue rather than deque is to make it clear you are
using only queue operations.
n
You must include
the header file <queue>
Member
functions of queue
n
push( ) inserts an element at
the back of the queue
n
back( ) returns the last
element in the queue
n
pop( ) removes the element at
the front of the queue
n
front( ) returns the element at
the front of the queue
n
size( ) returns the actual
number of elements
n
empty( ) returns true
when the queue is empty
Using
stacks and queues
n
The container
adaptors are used exactly like the containers themselves.
#include <stack>
#include <queue>
…..
stack<int> st;
queue<Person> per;
n
The only
difference between containers and container adaptors is that the container
adaptors are implemented using an STL container