Click here to Skip to main content
15,867,453 members
Articles / Desktop Programming / MFC

Stack Implementation using Templates

Rate me:
Please Sign up or sign in to vote.
4.60/5 (5 votes)
18 Dec 20011 min read 101.2K   944   17   3
Generic implementation of stacks LIFO

Introduction

A stack is an adaptor that provides a restricted subset of container functionality: it provides insertion, removal, and inspection of the element at the top of the stack. Stack is a "last in first out" (LIFO) data structure: the element at the top of a stack is the one that was most recently added. Stack does not allow iteration through its elements. Always remember stack of plates to understand stacks.

I decided to write this class last week because I needed it for a small project, but after a while I thought it will be nice to have a generic stack class that will be useful in C++.

Details

I have created two classes:

  • CStackX: This is a template class that implements LIFO with default size of 10000.
  • ArrayOutofBounds: Generic class that will print out the exception thrown when an error is encountered. To use this class, see the demo included. It is a very basic demo and any C++ beginner should understand it.

Diagrammatic Representation of a Stack After Push Operations

0
1
2
3
4
5

pop() will return 5 since it was the last pushed item, i.e., think of a plate put onto a stack of plates, the last plate put on will be removed. peek() will return 5 as well since it was the last plate dropped on.

Code Listing

C++
/*Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation.
*It is provided "as is" without express or implied warranty.
* kings_oz@yahoo.com
*/

// StackX.h: interface for the CStackX class.
//
/////////////////////////////////////////////

#ifndef _TREX_
#define _TREX_

#include <stdlib.h>
#include "ArrayBoundsEx.h"

#define ARRAY_MAX_SIZE 10000

template <class TRex>
class CStackX
{
public:
    CStackX();
    CStackX(long val);
    virtual ~CStackX();
    void push(TRex);
    TRex pop();
    TRex peek();
private:
    ArrayOutOfBounds *ex ;
    void setSize(long);
    long getSize();
    long arr_size;
    TRex *vect ;
    long top;
};

#endif

template <class TRex>
CStackX<TRex>::CStackX()
{
    //call super second constructor with value of 1000

    //create exception
    ex = new ArrayOutOfBounds();
    vect = new TRex[ARRAY_MAX_SIZE];
    top = -1;
}
template <class TRex>
CStackX<TRex>::CStackX(long val)
{
    ex = new ArrayOutOfBounds();
    setSize(val);
    vect = new TRex[arr_size];
    top = -1;
}
template <class TRex>
CStackX<TRex>::~CStackX()
{
    //delete array dynamically allocated
    delete ex;
    delete[] vect;
}
template <class TRex>
void CStackX<TRex>::push(TRex value)
{
    try
    {
        if(top != arr_size)
        {
            //top +=1;
            vect[++top] = value;
        }
        else
            throw ex;
    }
    catch(ArrayOutOfBounds * arrayExc)
    {
        arrayExc->printError("Max Value of Stack Reached oops.....\n");
        exit(1);
    }
}

template <class TRex>
TRex CStackX<TRex>::pop()
{
    try
    {
        if(top != -1)
            return vect[top--];
        else
            throw ex;
    }
    catch(ArrayOutOfBounds* exc)
    {
        exc->printError("End of Array  can't pop anymore ...\n");
        exit(1);
    }
}

template <class TRex>
TRex CStackX<TRex>::peek()
{
    try
    {
        if(top != -1)
            return vect[top];
        else
            throw ex;
    }
    catch(ArrayOutOfBounds* exc)
    {
        exc->printError("Peeking time closed nothing to see anymore...\n");
        exit(1);
    }
}

template <class TRex>
long CStackX<TRex>::getSize()
{
    return arr_size;
}

template <class TRex>
void CStackX<TRex>::setSize(long val)
{
    arr_size = val;
}

License

This article has no explicit license attached to it, but may contain usage terms in the article text or the download files themselves. If in doubt, please contact the author via the discussion board below.

A list of licenses authors might use can be found here.


Written By
kin
Europe Europe
no need for this information at this moment

Comments and Discussions

 
GeneralSuggestion Pin
Todd Smith19-Dec-01 10:26
Todd Smith19-Dec-01 10:26 
QuestionAnd this is needed why??????? Pin
Brian V Shifrin19-Dec-01 4:43
Brian V Shifrin19-Dec-01 4:43 
AnswerRe: And this is needed why??????? Pin
19-Dec-01 4:45
suss19-Dec-01 4:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.