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

本文介绍了一个通用模板栈类的实现细节,包括动态调整容量的方法及如何进行元素的压入与弹出操作。此外,还提供了栈类的友元运算符重载以支持标准输出流打印栈内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
#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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值