由于指针栈的特殊性,模板类中需要包含析构函数,复制构造函数,复制运算符等。
student.h
#ifndef STUENT_H_
#define STUDENT_H_
template <class Type>
class Stack{
private:
enum{MAX=10};
int stacksize;
Type *item;
int top;
public:
explicit Stack(int ss=MAX);
Stack(const Stack &st);
~Stack() {delete [] item;}
bool isempty() {return top==0;}
bool isfull() {return top==MAX;}
bool push(const Type &item);
bool pop(Type & item);
Stack & operator = (const Stack &st);
};
template <class Type>
Stack<Type>::Stack(int ss):stacksize(ss),top(0)
{
item = new Type [stacksize];
}
template <class Type>
Stack<Type>::Stack(const Stack &st)
{
stacksize = st.stacksize;
top=st.top;
item=new Type [st.stacksize];
for(int i=0;i<stacksize;i++)
item[i]=st.item[i];
}
template <class Type>
bool Stack<Type>::push(const Type & items)
{
if(top<stacksize)
{
item[top++]=items;
return true;
}
else
return false;
}
template <class Type>
bool Stack<Type>::pop(Type & items)
{
if(top>0)
{
items=item[--top];
return true;
}
else
return false;
}
template <class Type>
Stack<Type> & Stack<Type>::operator = (const Stack<Type> & st)
{
if(this==&st)
return *this;
delete [] item;
stacksize = st.stacksize;
top=st.top;
item = new Type [st.stacksize];
for(int i=0;i<stacksize;i++)
item[i]=st.item[i];
return *this;
}
#endif // STUENT_H_
main.cpp
#include<iostream>
#include"student.h"
#include<cstdlib>
#include<ctime>
using std::cin;
using std::cout;
using std::endl;
const int Num =10;
int main()
{
srand(time(0));
cout << "please enter stack size: ";
int stacksize;
cin >> stacksize;
Stack <const char *> st(stacksize);
const char * in[Num] = {
"1:hank gilgamesh","2:kiki ishtar","3:betty rocker","4:ian flagranti","5:wolfgang kibble",
"6:portia koop","7:joy almondo","8:xaverie paprika","9:juan moore","10:misha mache"
};
const char *out[Num];
int processed = 0;
int nextin =0;
while(processed<stacksize)
{
if(st.isempty())
st.push(in[nextin++]);
else if(st.isfull())
st.pop(out[processed++]);
else if(rand()%2&&nextin<Num)
st.push(in[nextin++]);
else
st.pop(out[processed++]);
}
for(int i=0;i<stacksize;i++)
cout << out[i] << endl;
cout << "bye.";
return 0;
}
运行结果: