-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcpp-data-structures-array-class-and-template.cpp
98 lines (73 loc) · 1.56 KB
/
cpp-data-structures-array-class-and-template.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
#include <iostream>
using namespace std;
template<class T>
class Array // a class should have data members and a member function
{
private:
T* A; // dynamically create the array that can be int or float
int size;
int length;
public:
Array() // non parameterized constructor
{
size = 10;
A = new T[10]; // created in Heap using T
length = 0;
}
Array(int sz) // parameterized constructor with desired size
{
size = sz;
length = 0;
A = new T[size]; // using T
}
~Array()
{
delete[]A;
};
void Display();
void Insert(int index, T x);
T Delete(int index); // return type is T
};
template<class T> // template declared before each function
void Array<T>::Display() // template class T
{
int i;
cout << "Elements are ";
for (i=0; i < length; i++)
cout << A[i] << " ";
cout << endl;
}
template<class T>
void Array<T>::Insert(int index, T x) // T parameter
{
if (index >= 0 && index <= length)
{
for (int i = length - 1; i >= index; i--)
A[i + 1] = A[i];
A[index] = x;
length++;
}
}
template<class T>
T Array<T>::Delete(int index) {
T x = 0; // T variable
if (index >= 0 && index < length)
{
x = A[index];
cout << "Deleted elements are ";
for (int i = index; i < length - 1; i++)
A[i] = A[i + 1];
length--;
}
return x;
}
int main() {
Array<int> arr(10); // class with <int>
arr.Insert(0, 5);
arr.Insert(1, 6);
arr.Insert(2, 9);
arr.Display(); // display 5, 6, 9,
cout << arr.Delete(0) << endl;
arr.Display(); // diplay 6, 9
return 0;
}