-
Notifications
You must be signed in to change notification settings - Fork 0
/
templatedClass.cpp
112 lines (112 loc) · 2.33 KB
/
templatedClass.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
//An example of using templated class to create stack depends on underlying array.
#include<iostream>
#include<cstdlib>
#define default_value 10
using namespace std;
template< class T > class Stack
{
public:
Stack(int = default_value);//default constructor
~Stack()//destructor
{delete [] values;}
bool push( T );
T pop();
bool isEmpty();
bool isFull();
private:
int size;
T *values;
int index;
};
template< class T > Stack<T>::Stack(int x):
size(x),//ctor
values(new T[size]),
index(-1)
{ /*empty*/ }
template< class T > bool Stack<T>::isFull()
{
if((index + 1) == size )
return 1;
else
return 0;
}
template< class T > bool Stack<T>::push(T x)
{
bool b = 0;
if(!Stack<T>::isFull())
{
index += 1;
values[index] = x;
b = 1;
}
return b;
}
template< class T > bool Stack<T>::isEmpty()
{
if( index == -1 )//is empty
return 1;
else
return 0; //is not empty
}
template< class T > T Stack<T>::pop()
{
T val = -1;
if(!Stack<T>::isEmpty())
{
val = values[index];
index -= 1;
}
else
{
cerr << "Stack is Empty : ";
}
return val;
}
int main()
{
Stack <double> stack1;
Stack <int> stack2(5);
int y = 1;
double x = 1.1;
int i, j;
cout << "\n pushed values into stack1: ";
for( i = 1 ; i <= 11 ; i++) //start enter 11 elements into stack
{
if(stack1.push(i*x))
cout << endl << i*x;
else
cout << "\n Stack1 is full: ";
}
cout << "\n\n popd values from stack1 : \n";
for( j = 1 ; j <= 11 ; j++)
cout << stack1.pop() << endl;
cout << "\n pushd values into stack2: ";
for( i = 1 ; i <= 6 ; i++) //start enter 6 elements into stack
{
if(stack2.push(i*y))
cout << endl << i*y;
else
cout << "\n Stack2 is full: ";
}
cout << "\n\n popd values from stack2: \n";
for( j = 1 ; j <= 6 ; j++)
cout << stack2.pop() << endl;
cout << endl << endl;
return 0;
}