c++template学习:基于数组的固定大小的模版类栈

本文介绍了一个通用栈数据结构的模板实现,包括基本操作如Push、Pop等,并提供了一个简单的使用示例。
头文件:include/Stack.h
#ifndef _STACK_H_
#define _STACK_H_

#include 
<assert.h>

namespace DataStructure
...{

template
<typename DataType>
class Stack
...{
public:
    Stack(
int StackSize);
    
~Stack();
    
bool Pop(DataType* Out);
    
bool Push(DataType& In);
    
bool IsEmpty();
    
bool IsFull();
    
bool GetTop(DataType* Out);
    
int Count();
private:
    Stack();
    Stack(
const Stack& rsh);
    Stack
& operator=(Stack& rsh);
//-----------------------------------------------------------------------------
protected:

private:
    
const int STACK_SIZE;
    
int m_Top;
    DataType
* m_Data;
}
;

#include 
"../src/Stack.hpp"

}
  //end namespace

#endif


文件:src/Stack.hpp

template
<typename DataType>
Stack
<DataType>::Stack(int StackSize):
    STACK_SIZE(StackSize),
    m_Top(
0)
...{
    assert(StackSize
>0);
    m_Data 
= new DataType[StackSize];
}


template
<typename DataType>
Stack
<DataType>::~Stack()
...{
    delete[] m_Data;
    m_Data 
= NULL;
}


template
<typename DataType>
bool Stack<DataType>::Pop(DataType* Out)
...{
    
if (0==m_Top)
    
...{
        
return false;
    }

    m_Top
--;
    
*Out = m_Data[m_Top];
    
return true;
}


template
<typename DataType>
bool Stack<DataType>::Push(DataType& In)
...{
    
if (m_Top>=STACK_SIZE-1)
    
...{
        
return false;
    }

    m_Data[m_Top] 
= In;
    m_Top
++;
    
return true;
}


template
<typename DataType>
bool Stack<DataType>::IsEmpty()
...{
    
return 0==m_Top;
}


template
<typename DataType>
bool Stack<DataType>::IsFull()
...{
    
return m_Top==STACK_SIZE-1;
}


template
<typename DataType>
bool Stack<DataType>::GetTop(DataType* Out)
...{
    
if (0==m_Top)
    
...{
        
return false;
    }

    
*Out = m_Data[m_Top];
    
return true;
}


template
<typename DataType>
int Stack<DataType>::Count()
...{
    
return m_Top-1;
}



调用例子:

#include 
"include/Stack.h"

using namespace DataStructure;

void Test()
...{
    Stack
<int> s(100);
    
int temp = 1;
    
if (!s.Push(temp))
    
...{
        printf(
"栈满!");
        
return;
    }

    
if (!s.Pop(&temp))
    
...{
        printf(
"栈空! ");
        
return;
    }

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值