Create your own stack based on deque : deque « Deque « C++






Create your own stack based on deque

  
 

/* The following code example is taken from the book
 * "The C++ Standard Library - A Tutorial and Reference"
 * by Nicolai M. Josuttis, Addison-Wesley, 1999
 *
 * (C) Copyright Nicolai M. Josuttis 1999.
 * Permission to copy, use, modify, sell and distribute this software
 * is granted provided this copyright notice appears in all copies.
 * This software is provided "as is" without express or implied
 * warranty, and with no claim as to its suitability for any purpose.
 */
#include <iostream>
#include <deque>
#include <exception>

using namespace std;

template <class T>
class Stack {
  protected:
    std::deque<T> c;        // container for the elements

  public:
    /* exception class for pop() and top() with empty stack
     */
    class ReadEmptyStack : public std::exception {
      public:
        virtual const char* what() const throw() {
            return "read empty stack";
        }
    };
  
    // number of elements
    typename std::deque<T>::size_type size() const {
        return c.size();
    }

    // is stack empty?
    bool empty() const {
        return c.empty();
    }

    // push element into the stack
    void push (const T& elem) {
        c.push_back(elem);
    }

    // pop element out of the stack and return its value
    T pop () {
        if (c.empty()) {
            throw ReadEmptyStack();
        }
        T elem(c.back());
        c.pop_back();
        return elem;
    }

    // return value of next element
    T& top () {
        if (c.empty()) {
            throw ReadEmptyStack();
        }
        return c.back();
    }
};


int main()
{
   try {
      Stack<int> st;

      // push three elements into the stack
      st.push(1);
      st.push(2);
      st.push(3);

      // pop and print two elements from the stack
      cout << st.pop() << ' ';
      cout << st.pop() << ' ';

      // modify top element
      st.top() = 77;

      // push two new elements
      st.push(4);
      st.push(5);

      // pop one element without processing it
      st.pop();

      /* pop and print three elements
       * - ERROR: one element too many
       */
      cout << st.pop() << ' ';
      cout << st.pop() << endl;
      cout << st.pop() << endl;
   }
   catch (const exception& e) {
      cerr << "EXCEPTION: " << e.what() << endl;
   }
}

/* 
3 2 4 77
EXCEPTION: read empty stack

 */        
    
  








Related examples in the same category

1.Use generic deque to store integers
2.Use generic deque to store chars
3.Use generic deque to store strings
4.Initialize deque with 26 copies of the letter x
5.create a deque
6.Use std::copy to print out all elements in a deque
7.deque.push_back( value )
8.deque.push_front( value )
9.Combine insert and end to add elements to a deque
10.Save transformed data from vector to deque (Vector1 + Vector2 = Result (in Deque))