stack |
A stack
is an adapter that can use any container that supports push_back()
and pop_back() as a first-in, last-out data
structure. This section provides an overview of stack
.
Because adapters do not support
iteration, a stack has no associated iterator.
A stack
is implemented as a class comprised of inline functions converting push()
and pop() messages into push_back()
and pop_back() messages. Although a stack
can use any kind of sequential container as its underlying data structure, a deque
or vector yields the best performance.
A stack
is useful for implementing strictly first-in, last-out data structures when
direct indexed access to the items is not performed.
In addition to the common set of collection operations, stacks offer the following behaviors.
void
push( const T& value )stack .void
pop()stack . Note that pop()
does not return a value.T&
top() The following example of a stack
uses a deque as its underlying data structure.
#include <iostream>
#include <deque>
#include <stack>
void
main()
{
stack< int, deque< int > > s;
s.push( 42 );
s.push( 101 );
s.push( 69 );
while ( !s.empty() )
{
cout << s.top() << "\n";
s.pop();
}
}
69
101
42
Following is the same program,
this time using a list
as the underlying data structure.
#include <iostream>
#include <list>
#include <stack>
void
main()
{
stack< int, list< int > > s;
s.push( 42 );
s.push( 101 );
s.push( 69 );
while ( !s.empty() )
{
cout << s.top() << "\n";
s.pop();
}
}
69
101
42
Copyright©1994-2026 Recursion
Software LLC
All Rights Reserved - For use by licensed users only.