1,stack.h
#ifndef STACK_H_
#define STACK_H_
//1,定义类模板,
//模板类开头代码:
//template <class Type> 或者 template <typename Type>
//模拟一个栈的模板类
template <class Type>
class Stack
{
private :
const static int MAX = 100; //栈容纳的最多数据
Type items[MAX]; //储存栈数据的数组
int top; //栈顶
public:
Stack();
bool isempty();
bool isfull();
bool push(const Type & item);
bool pop(Type & item);
};
//由于模板的特殊性 所以模板不能单独编译 必须与特定的模板实例化请求一起使用 所以实现放在下面
template <class Type>
Stack<Type>::Stack()
{
top = 0;
}
template <class Type>
bool Stack<Type>::isempty()
{
return top == 0;
}
template <class Type>
bool Stack<Type>::isfull()
{
return top == MAX;
}
template <class Type>
bool Stack<Type>::push(const Type & itme)
{
if(top < MAX)
{
items[top++] = itme;
return true;
}
else
return false;
}
template <class Type>
bool Stack<Type>::pop(Type & item)
{
if(top > 0)
{
item = items[--top];
return true;
}
else
return false;
}
#endif
2,mian
//使用模板类
#include "stack.h"
#include <iostream>
#include <string>
using namespace std;
void main()
{
Stack<int>oneInt;
int i = 0;
while(!oneInt.isfull())
{
oneInt.push(i++);
}
while(!oneInt.isempty())
{
int a;
oneInt.pop(a);
cout.width(2); //设置输出宽度
cout << a;
a % 10 == 0 ? cout << "\n" : cout << " ";
/*
输出结果:
99 98 97 96 95 94 93 92 91 90
89 88 87 86 85 84 83 82 81 80
79 78 77 76 75 74 73 72 71 70
69 68 67 66 65 64 63 62 61 60
59 58 57 56 55 54 53 52 51 50
49 48 47 46 45 44 43 42 41 40
39 38 37 36 35 34 33 32 31 30
29 28 27 26 25 24 23 22 21 20
19 18 17 16 15 14 13 12 11 10
9 8 7 6 5 4 3 2 1 0
*/
}
cout << "\n";
Stack<string> twoString;
i = 0;
while(!twoString.isfull())
{
string str = "a";
char ch = (i++) + '0';
if(i == 10)
{
i = 0;
}
str += ch;
twoString.push(str);
}
int a = 99;
while(!twoString.isempty())
{
string str;
twoString.pop(str);
cout << str;
(a --) % 10 == 0 ? cout << "\n" : cout << " ";
/*
输出结果:
99 98 97 96 95 94 93 92 91 90
89 88 87 86 85 84 83 82 81 80
79 78 77 76 75 74 73 72 71 70
69 68 67 66 65 64 63 62 61 60
59 58 57 56 55 54 53 52 51 50
49 48 47 46 45 44 43 42 41 40
39 38 37 36 35 34 33 32 31 30
29 28 27 26 25 24 23 22 21 20
19 18 17 16 15 14 13 12 11 10
9 8 7 6 5 4 3 2 1 0
*/
}
system("pause");
}