pgrm_024.cpp
Problem Statement
pgrm_024.cpp
WAP to find max from an array using template class and no-inline template function
Source Code
cpp
#include <iostream>
using namespace std;
template <class T>
class Max {
private:
T *a;
int s;
public:
Max() {
cout << "Array size: ";
cin >> s;
a = new T[s];
}
void getData();
T find_max();
~Max() {
delete[] a;
cout << "obj deleted.";
}
};
template <class T>
void Max<T>::getData() {
cout << "Enter elements: ";
for (int i = 0; i < s; ++i) {
cin >> a[i];
}
}
template <class T>
T Max<T>::find_max() {
T m = a[0];
for (int i = 1; i < s; i++) {
if (m < a[i]) {
m = a[i];
}
}
return m;
}
int main() {
Max<int> obj;
obj.getData();
cout << "Max element: " << obj.find_max() << endl;
Max<float> obj2;
obj2.getData();
cout << "Max element: " << obj2.find_max() << endl;
return 0;
}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
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