------------------------------------------------------------------------------
MC logo
Array Template Stack
[^] CSc 220 Home
------------------------------------------------------------------------------
[Introduction] [Boolean and Control] [Functions] [Arrays and Pointers] [Dynamic Arrays] [Array Errors] [Command Array] [Standard Containers] [Structs and Classes] [Automatic Pointer] [Multi-File Programs] [Copying Objects] [Templates] [Inheritance] [Plain C I/O] [Type Odds And Ends] [Plain C Strings] [File I/O]
[Template Functions] [Template Generalized Stack] [Template Generalized Stack Driver] [Array Template Stack] [Array Template Test Driver] [Generalized Safe Array] [Safe Array Demo] [Vector Iterator Demo]
stackt2.h
//
//*****************************************************************************
//* C++ stack using templates.  Note that everything is here; there is no
//* implementation CC file.
//*****************************************************************************
//

#ifndef _STACKT_H_
#define _STACKT_H_

#include <stdexcept>

// This is a template class.  The name T stands for any type.  By saying
// Stack<whatever>, we create a stack of whatevers.
template <class T, int size = 50>
class Stack
{
 private:
        T data[size];
        int top_elt;
 public:
        // Create an empty stack.
        Stack() { top_elt = -1; }

        // Add an element to the stack.  Note that you must send a pointer,
        // and the stack actually stores the pointer.
        void push(T e)
        {
                data[++top_elt] = e;
        }

        // Pop the stack and return the top item pointer.  If the stack is
        // empty, return the null pointer.
        const T& pop() {
                if(empty()) throw std::runtime_error("Pop on empty stack");
                else return data[top_elt--];
        }

        // Return the top item pointer.  If none, return the null pointer.
        const T& top() const {
                if(empty()) std::runtime_error("Top on empty stack");
                return data[top_elt];
        }

        // Tell if the stack is empty.
        bool empty() const { return top_elt == -1; }
};

#endif