pgrm_023.cpp
Problem Statement
pgrm_023.cpp
WAP to implement linear search template class and template function
Source Code
cpp
#include<iostream>
using namespace std;
template <class T>
class LinearSearch {
private:
T *arr;
int size;
T key;
public:
LinearSearch(int n) {
size = n;
arr = new T[size];
cout << "Array Size: " << size << endl;
cout << "Enter elements: ";
for(int i = 0; i < size; i++) {
cin >> arr[i];
}
cout << "Enter key: ";
cin >> key;
}
int search() {
for(int i = 0; i < size; i++) {
if(arr[i] == key)
return i;
}
return -1;
}
};
int main() {
LinearSearch<int> obj(5);
int index = obj.search();
if(index != -1)
cout << "Key found at: " << index << endl;
else
cout << "Key not found!" << endl;
LinearSearch<double> obj2(5);
index = obj2.search();
if(index != -1)
cout << "Key found at: " << index << endl;
else
cout << "Key not found!" << 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
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