C++ Stacks

C/C++ Reference

empty
Syntax:
  #include <stack>
  bool empty() const;

The empty() function returns true if the stack has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a while loop to clear a stack and display its contents in reverse order:

 stack<int> s;
 for( int i = 0; i < 5; i++ ) {
   s.push(i);
 }
 while( !s.empty() ) {
   cout << s.top() << endl;
   s.pop();
 }              
Related topics:

pop
Syntax:
  #include <stack>
  void pop();

The function pop() removes the top element of the stack and discards it.

Related topics:

push
Syntax:
  #include <stack>
  void push( const TYPE& val );

The function push() adds val to the top of the current stack.

For example, the following code uses the push() function to add ten integers to the top of a stack:

   stack<int> s;
   for( int i=0; i < 10; i++ )
     s.push(i);         
Related topics:

size
Syntax:
  #include <stack>
  size_type size() const;

The size() function returns the number of elements in the current stack.

Related topics:

Stack constructors
Syntax:
  #include <stack>
  stack();
  stack( const Container& con );

Stacks have an empty constructor and a constructor that can be used to specify a container type.


top
Syntax:
  #include <stack>
  TYPE& top();

The function top() returns a reference to the top element of the stack.

For example, the following code removes all of the elements from a stack and uses top() to display them:

   while( !s.empty() ) {
     cout << s.top() << " ";
     s.pop();
   }            
Related topics: