C++實例 | 棧類模版
#include <stdlib.h>
#include <iostream>
using namespace std;
template <class T>
class Stack {
public:
Stack(int size);
Stack(const Stack &p);
virtual ~Stack();
void Push(const T &e);
const T &Pop();
const T &Peek() const;
bool IsEmpty() const;
private:
T *buff;
int max;
int top;
};
template <class T>
Stack<T>::Stack(int size) {
buff = new T[max = size];
top = -1;
}
template <class T>
Stack<T>::Stack(const Stack &p) {
buff = new T[max = p.max];
top = p.top;
for (int i = 0; i <= top; i++) buff[i] = p.buff[i];
}
template <class T>
Stack<T>::~Stack() {
delete[] buff;
}
template <class T>
void Stack<T>::Push(const T &e) {
if (top >= max - 1)
cout << "overflow!" << endl;
else
buff[++top] = e;
}
template <class T>
const T &Stack<T>::Pop() {
if (top < 0) {
cout << "underflow!" << endl;
return buff[0];
} else
return buff[top--];
}
template <class T>
const T &Stack<T>::Peek() const {
if (top < 0) {
cout << "underflow!" << endl;
return buff[0];
} else
return buff[top];
}
template <class T>
bool Stack<T>::IsEmpty() const {
return top < 0;
}
int main() {
Stack<double> DoubleStack(
10);
Stack<int> IntStack(
15);
for (double i = 1.0; i <= 20.0; i += 2.0) DoubleStack.Push(i);
for (int j = 0; j < 75; j += 5) IntStack.Push(j);
Stack<double> DoubleStack2(DoubleStack);
while (!DoubleStack2.IsEmpty()) cout << DoubleStack2.Pop() << " ";
cout << endl;
Stack<int> IntStack2(IntStack);
while (!IntStack2.IsEmpty()) cout << IntStack2.Pop() << " ";
cout << endl;
while (!DoubleStack.IsEmpty()) cout << DoubleStack.Pop() << " ";
cout << endl;
while (!IntStack.IsEmpty()) cout << IntStack.Pop() << " ";
cout << endl;
system("pause");
}