ADTstack and the STL stack Container Adaptor
Like the queue, the stack is a very simple and straightforward abstract data type, but is nevertheless one of the most useful in programming.
The idea of a stack in the context of programming is in fact what we normally think of as a "stack" of anything: a stack of books, a stack of plates, a stack of bills to pay, and so on. The way we usually use a stack is to put a new item added to the stack on "top" of the stack, and as anyone who has tried to get at the seventh book down in a stack of books knows, it is easier by far to remove (or access in any other way) the item "on top" than it is to access any other item in the stack.
The stack abstract data type enforces this behavior, which is usually given the acronym LIFO (Last In, First Out). The STL stack is not a "first class" container in its own right, like the vector, deque and list, but is instead based on a tightly controlled interface to an underlying deque container class (by default). This is why it is called a container "adaptor".
stack Operations | |
---|---|
Generic (ADT) | Specific (STL) |
Construct a stack |
stack<T> s;
stack<T> s(otherContainer); |
Test for emptiness | empty() |
Add value to top | push(val) |
Remove top value | pop() |
Get top value, without removing it | top() |
Get current size | size() |
The above interface for a stack contains the usual operations you would find if you looked up "stack" in most any textbook on data structures, and these are in fact the operations provided by the STL.
We need to say something about the second constructor. The "otherContainer" that may be used to initialize a stack cannot be just any other container. It must, in fact, be another stack having the same kind of components as the stack being constructed, or another container of the type on which the stack is based (which, by default, is the deque) and also having the same kind of components as the stack being constructed.
The stack container adaptor does not support any iterators.
The stack container adaptor should be used in any situation where components are being added to and removed from the container in LIFO fashion.