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