Quick Intro to the C++ stack from the Standard Template Library

Member functions

Member

Description

stack()

The default constructor. Creates an empty stack.

stack(const stack&)

The copy constructor.

stack& operator=(const stack&)

The assignment operator.

bool empty() const

Returns true if the stack contains no elements, and false otherwise. S.empty() is equivalent to S.size() == 0.

size_type size() const

Returns the number of elements contained in the stack.

value_type& top()

Returns a mutable reference to the element at the top of the stack. Precondition: empty() is false.

const value_type& top() const

Returns a const reference to the element at the top of the stack. Precondition: empty() is false.

void push(const value_type&)

Inserts x at the top of the stack. Postconditions: size() will be incremented by 1, and top() will be equal to x.

void pop()

Removes the element at the top of the stack. Precondition: empty() is false. Postcondition: size() will be decremented by 1

bool operator==(const stack&, const stack&)

Compares two stacks for equality. Two stacks are equal if they contain the same number of elements and if they are equal element-by-element. This is a global function, not a member function.

bool operator<(const stack&, const stack&)

Lexicographical ordering of two stacks. This is a global function, not a member function.

 

Web Pages with Help with stack

http://www.cppreference.com/cppstack.html
http://cis.stvincent.edu/swd/stl/stacks/stacks.html

Example use of stack

//
// stack.cpp
//
 #include <iostream>
 using namespace std;
 #include <stack>
 #include <string>
 int main(void)
 {
   stack<int> s;
   s.push(1);
   s.push(2);
   cout << s.top() << endl;
   s.pop();
   cout << s.top() << endl;
   s.pop();
 
   stack<string> ss;
   int i;
   for (i = 0; i < 10; i++)
   {
     ss.push(string(i+1,'a'));
     cout << ss.top() << endl;
   }
   for (i = 0; i < 10; i++)
   {
     cout << ss.top() << endl;
     ss.pop();
   }
   return 0;
 }