现在的位置: 首页 > 综合 > 正文

C++ 学习练手 – 数组型栈的模板实现

2018年04月06日 ⁄ 综合 ⁄ 共 2097字 ⁄ 字号 评论关闭
 

#ifndef __STACKPRACTICE_H__
#define __STACKPRACTICE_H__ 1
namespace FengChen
{
    template 
<class Type> class Stack;
    
    template 
<class T>
    std::ostream
& operator<<(std::ostream& os, const Stack<T>& S)
    
{
        os
<<"Stack:< ";
        
for(int i = 0; i < S.m_Length; i++) os<<S.m_Array[i]<<" ";
        os
<<" --Top>";

        
return os;
    }



    template 
<class Type> class Stack
    
{
        friend std::ostream
& operator<< <Type> (std::ostream&const Stack<Type>&);
    
public:
        Stack():m_Capicity(
64 * 1024 / sizeof(Type)),m_Length(0),m_Array(0
        
{
            
if( (m_Array = new Type[m_Capicity]) == 0
                
throw std::runtime_error("Initialize failed, not enough memory!");
        }


        Stack(
int Size):m_Length(0),m_Array(0)
        
{
            assert(Size 
> 1);
            m_Capicity 
= Size;
            
            
if( (m_Array = new Type[m_Capicity]) == 0
                
throw std::runtime_error("Initialize failed, not enough memory!");
        }


        
~Stack()
        
{
            delete[] m_Array;
            m_Array 
= 0;
        }


        inline 
int Length() const{return m_Length;}

        inline 
int Capacity() const{return m_Capicity;}
        
const Type& Top() const return m_Array[m_Length - 1]; }
        
void Push(const Type& value)
        
{
            
if(m_Length + 1 > m_Capicity) this->Resize();
            m_Array[m_Length
++= value;
        }


        
const Type& Pop()
        
{
            
if(m_Length < 1throw std::runtime_error("Stack is null!");
            
return m_Array[m_Length--];
        }

    
private:
        
int m_Capicity;
        
int m_Length;
        Type
* m_Array;

        
void Resize()
        
{
            
int newSize = 2*m_Capicity;
            
int* newArray = 0;

            
if((newArray = new Type[newSize] ) == 0
                
throw std::runtime_error("Resize failed, not enough memory!");
            memmove_s(newArray, m_Capicity
*sizeof(Type), m_Array, m_Capicity*sizeof(Type));

            delete [] m_Array;
            m_Capicity 
= newSize;
            m_Array 
= newArray;
        }

    }
;
}


#endif

抱歉!评论已关闭.