Pushok

Little update of stack class.

Apr 11th, 2011
445
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.24 KB | None | 0 0
  1. template<typename T> class CStack {
  2. public:
  3.     static enum {CStack_StackEmpty, CStack_BadMemory};
  4.  
  5.     unsigned int size()
  6.     {
  7.         return StackSize;
  8.     }
  9.  
  10.     bool empty()
  11.     {
  12.         return StackSize == 0;
  13.     }
  14.  
  15.     T pop()
  16.     {
  17.         if(StackIter == 0) throw (int)CStack_StackEmpty;
  18.  
  19.         return _Stack[--StackIter];
  20.     }
  21.  
  22.     void push(T j)
  23.     {
  24.         if(StackSize >= StackIter && _Stack != 0)
  25.         {
  26.             T* _newstack = (T*)malloc(sizeof(T) * (StackSize + 1));
  27.  
  28.             if(_newstack == NULL)
  29.             {
  30.                 free(_newstack);
  31.                 this->~CStack();
  32.                 throw (int)CStack_BadMemory;
  33.             }
  34.  
  35.             for(int i=0;i<StackSize;i++)
  36.                 _newstack[i] = _Stack[i];
  37.            
  38.             free(_Stack);
  39.  
  40.             _Stack = _newstack;
  41.         }
  42.         else if (_Stack == 0)
  43.         {
  44.             _Stack = (T*)malloc(sizeof(T) * (StackSize == 0 ? 1 : StackSize));
  45.             if(_Stack == 0)
  46.             {
  47.                 this->~CStack();
  48.                 throw (int)CStack_BadMemory;
  49.             }
  50.         }
  51.  
  52.         _Stack[StackSize++] = j;
  53.  
  54.         StackIter = StackSize;
  55.  
  56.     }
  57.  
  58.     void clear()
  59.     {
  60.         StackIter = 0;
  61.     }
  62.  
  63.     void allclear() // useless
  64.     {
  65.         free(_Stack);
  66.         StackIter = StackSize = 0;
  67.     }
  68.  
  69.     CStack()
  70.     {
  71.         StackIter = StackSize = 0;
  72.         _Stack = NULL;
  73.     }
  74.  
  75.     ~CStack()
  76.     {
  77.         free(_Stack);
  78.         StackIter = StackSize = 0;
  79.     }
  80.  
  81. private:
  82.     unsigned int StackSize, StackIter;
  83.     T* _Stack;
  84. };
Advertisement
Add Comment
Please, Sign In to add comment