Stacktp.h--A stack template
#ifndef stacktp_h_
#define STACKTP_H_
template <class type>
class Stack
{
private:
enum {MAX = ten};
Type Items[max];
int top; Index for top stack item 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>::p ush (const Type & Item)
{
if (Top < MAX)
{
items[top++] = Item;
return true;
}
else return
false;
Template <class type>
bool Stack<type>::p OP (Type & Item)
{
if (Top > 0)
{
item = Items[--top];
return true;
}
else return
false;
#endif
Stacktem.cpp--Testing teh template Stack class
#include <iostream> #include <string> #include <cctype> #include "stacktp.h" using namespace std;
int main () {stack<string> st;
Char ch;
String po;
cout << "Please enter a to add a purchase order,\n" << "P-Process a PO, or Q to quit.\n";
while (CIN >> ch && toupper (ch)!= ' Q ') {while (Cin.get ()!= ' \ n ') continue;
if (!isalpha (CH)) continue;
Switch (CH) {case ' a ': Case ' a ': cout << "Enter A PO number to add:";
CIN >> PO;
if (St.isfull ()) cout << "Stack already full\n";
else St.push (PO);
Break
Case ' P ': Case ' P ': if (St.isempty ()) cout << "Stack already empty\n";
else {st.pop (PO);
cout << "PO #" << po << "popped\n";
Break
} cout << "Please enter a to add a purchase order,\n" << "P to process a PO, or Q to quit.\n";
} cout << "bye\n";
return 0; }
Output:
wang@wang:~/c++$./a.out
Please enter a to add a purchase order,
P to process a PO, or Q to quit.
A
Enter a PO number to Add:red911porsche
Please enter a to add a purchase order,
P to process a PO, or Q to quit.
P
PO #red911porsche popped
Please enter a to add a purchase order,
P to process a PO, or Q to quit.
P
Stack already empty
Please enter a to add a purchase order,
P to process a PO, or Q to quit.
Q
Bye