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
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
#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()
{
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 ex;
delete[] vect;
}
template <class TRex>
void CStackX<TRex>::push(TRex value)
{
try
{
if(top != arr_size)
{
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;
}
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