#pragma once
const int INIT_SIZE = 100;
const int INCRENT_SIZE = 10;
template <typename T>
class CStack
{
private:
T m_pBase;/基址*/
int m_nSize;
int m_nTop;
public:
CStack()
{
m_pBase = new T[INIT_SIZE];
m_nSize = INIT_SIZE;
m_nTop = 0;
}
~CStack(void)
{
delete [] m_pBase;
}
bool IsEmpty()const
{
return m_nTop == 0;
}
void Push(const T& val)
{
//空间已满
if (m_nTop == m_nSize)
{
//增加
T newBase = new T[m_nSize+INCRENT_SIZE];
//复制原来的数据
::memcpy(newBase,m_pBase,m_nSizesizeof(T));
//删除原来的空间
delete []m_pBase;
//新的空间地址
m_pBase = newBase;
m_nSize += INCRENT_SIZE;
}
m_pBase[m_nTop++] = val;
}
int Pop(T& val)
{
if (m_nTop)
{
val = m_pBase[–m_nTop];
return 0;
}
return -1;
}
};
下面是个小的测试程序
// StackTest.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include "Stack.h" void DecToOthers(int decVal,const int x) { CStack<int> stack; while (decVal) { stack.Push(decVal%x); decVal = decVal / x; } while(!stack.IsEmpty()) { int n; stack.Pop(n); std::cout<<n; } std::cout<<std::endl; } int _tmain(int argc, _TCHAR* argv[]) { DecToOthers(1348,8); DecToOthers(128,2); CStack<int> stack; for (int i=0;i<200;i++) { stack.Push(i); } while(!stack.IsEmpty()) { int n; stack.Pop(n); std::cout<<n<<" "; } return 0; }