头文件:StackTP.h
#ifndef __STACKTP_H__
#define __STACKTP_H__
template<typename T>
class Stack
{
public:
Stack();
bool IsFull();
bool IsEmpty();
bool Push(const T &x);
bool Pop(T &x);
int Lenth();
void Show();
private:
enum{MAX = 10};//枚举类型是常数,类似#define MAX 10
T item[MAX];
int top;
};
template<typename T>
Stack<T>::Stack()
{
top = 0;
}
template<typename T>
bool Stack<T>::IsFull()
{
return top == MAX;
}
template<typename T>
bool Stack<T>::IsEmpty()
{
return top == 0;
}
template<typename T>
bool Stack<T>::Push(const T &x)
{
if (IsFull())
{
std::cout << "the stack is full!" << std::endl;
return false;
}
item[top++] = x;
return true;
}
template<typename T>
bool Stack<T>::Pop(T &x)
{
if ( IsEmpty() )
{
std::cout << "the stack is empty!" << std::endl;
return false;
}
x = item[--top];
return true;
}
template<typename T>
int Stack<T>::Lenth()
{
return top;
}
template<typename T>
void Stack<T>::Show()
{
for (int i = 0; i < top; ++i)
{
std::cout << item[i] << " ";
}
cout << std::endl;
}
#endif
测试程序1:
#include"StackTP.h"
#include<iostream>
#include<stdlib.h>
using std::cout;
using std::endl;
int main()
{
Stack<int> s;
for (int i = 0; i < 10; ++i)
{
s.Push(i);
}
cout << s.Lenth() << endl;
s.Show();
int item;
for (int i = 0; i < 9; ++i)
{
s.Pop(item);
}
s.Show();
system("pause");
return 0;
}
测试程序2:
//使用字符串作为购货订单ID
#include<iostream>
#include<string>
#include<ctype.h>//toupper(将字母转化为大写字母) isalpha(判断输入的是否为英文字符)
#include"StackTP.h"
using std::cin;
using std::cout;
using std::endl;
int main()
{
Stack<std::string> st;
char ch;
std::string po;
cout << "please enter A to add a purchase order" << endl;
cout << "P to process a PO , or Q to quit" << endl;
while (cin >> ch && toupper(ch) != 'Q')
{
while (cin.get() != '\n')//\n也会打入缓冲区中,此句略过\n,即如果读取的是\n 则继续读取,否则结束读取,执行下面语句
continue;
if (!isalpha(ch))//判断输入的字符是否为英文字符
{
cout << '\a';//如果输入的不是英文字符发出警告
continue;
}
switch (ch)
{
case 'A':
case 'a':
cout << "enter a PO number to add:";
cin >> po;
if (st.IsFull())
cout << "stack is full" << endl;
else
st.Push(po);
break;
case 'P':
case 'p':
if (st.IsEmpty())
cout << "stack is empty" << endl;
else
{
st.Pop(po);
cout << "PO #" << po << "popped" << endl;
break;
}
default:
break;
}
cout << "please enter A to add a purchase order" << endl;
cout << "P to process a PO , or Q to quit" << endl;
}
return 0;
}