The following is a data structure, stack, implemented using a C ++ template. I hope to help others and give some comments! After all, I rarely use templates.
# Ifndef _ STACK_H_INCLUDED
# Define _ STACK_H_INCLUDED
Template <typename T>
Class _ stack
{
Public:
_ Stack (size_t _ capacity = 1): capacity (_ capacity), pArry (new T [_ capacity]), length (0), pTop (pArry ){}
~ _ Stack () {delete [] pArry ;}
Void ClearStack ()
{
Length = 0;
PTop = pArry;
}
Bool IsEmpty () const {return length = 0 ;}
Size_t GetSize () const {return length ;}
Void Push (T & e );
T Pop ()
{
-- Length;
Return * (-- pTop );
}
T & GetTop () const;
Void vist () const;
Private:
Size_t capacity;
T * pArry;
Size_t length;
T * pTop;
};
Template <typename T>
T & _ stack <T>: GetTop () const
{
If (! IsEmpty ())
Return * (pTop-1 );
Else
Return * pTop;
}
Template <typename T>
Void _ stack <T>: Push (T & e)
{
++ Length;
If (length <capacity)
{
* PTop = e;
++ PTop;
}
Else
{
T * ptmp (new T [2 * capacity]);
T * const phead (ptmp );
T * pT (pArry );
For (int I = 0; I <length; ++ I)
{
* Ptmp = * pT;
++ Ptmp;
++ PT;
}
Capacity * = 2;
Delete [] pArry;
* (++ Ptmp) = e;
PTop = ++ ptmp;
PArry = phead;
}
}
Template <typename T>
Void _ stack <T >:: vist () const
{
T * ptmp (pTop );
While (ptmp! = PArry)
{
Std: cout <* (-- ptmp) <"";
}
}
# Endif // _ STACK_H_INCLUDED