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 .

Iterator Type

Because adapters do not support iteration, a stack has no associated iterator.

Implementation

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.

Common Uses

A stack is useful for implementing strictly first-in, last-out data structures when direct indexed access to the items is not performed.

Interface

In addition to the common set of collection operations, stacks offer the following behaviors.

push
void push( const T& value )
Pushes a copy of value onto the stack .
pop
void pop()
Erases the top value from the stack . Note that pop() does not return a value.
top
T& top()
Returns a reference to the top value.

The following example of a stack uses a deque as its underlying data structure.

Example <ospace/osstd/examples/stack1.cpp>
#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.

Example <ospace/osstd/examples/stack2.cpp>
#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.