Create a class Template which stores an array. Include member function .
(i) To search an element in the array.
(ii) To find the sum of elements of an array
(iii) To find the largest elements of an array
Objective
Write a C++ program using a Class Template to perform operations (Search, Sum, Largest) on a generic array.
Algorithm / Approach
- Define
template <class T>before the class. - Declare an array of the generic type:
T arr[5]. - Implement
input(),search(),sum(), andlargest()using the generic placeholderTfor all temporary variables. - In
main(), instantiate the generic class.
main.cpp
#include
using namespace std;
template
class Test{
public:
T arr[5];
void input() {
T x;
cout<<"Enter 5 Elements ";
for(int i =0; i<5; i++) {
cin>>x;
arr[i] = x;
}
}
void search() {
T a;
int flag = 0;
int i=0;
cout<<"Enter Element to search ";
cin>>a;
for(i = 0; i<5; i++) {
if(arr[i]==a) {
flag = 1;
break;
}
}
if(flag ==1 ) {
cout<<"Found At "<< i<< endl;
}
else {
cout<<"Element NOT found "<< endl;
}
}
void sum() {
T s =0;
for(int i=0; i<5; i++) {
s = s+ arr[i];
}
cout<<"Sum = "<< s<< endl;
}
void largest() {
T max= arr[0];
for(int i = 0;i<5; i++) {
if(max< arr[i]) {
max = arr[i];
}
}
cout<<"Maximum = "<< max<< endl;
}
};
int main() {
Test t;
t.input();
t.search();
t.sum();
t.largest();
return 0;
}
Expected Output
Enter 5 Elements 1 4 8 6 4 Enter Element to Search 5 Element NOT found Sum = 23 Maximum = 8
Explanation of the Program
- This demonstrates how powerful templates can be. You can write complex data structure logic once, and instantly use it for arrays of floats, integers, or strings just by changing the template parameter.
- Note on the provided code: It contains massive syntax errors that will prevent compilation. The include directive is empty (
#includeinstead of#include<iostream>). The template declaration is empty (templateinstead oftemplate<class T>). And the object instantiation in main is missing the data type (Test t;instead ofTest<int> t;).
Complexity
Time Complexity
O(n) - For searching, summing, and finding the max.
Space Complexity
O(n) - To store the array.
Common Mistakes
- Syntax Error: Empty
#includedirective. - Syntax Error: Empty
templatedeclaration. It must include the generic parameter (e.g.,template<class T>). - Syntax Error: Failing to specify the data type when instantiating a template class (e.g., writing
Test t;instead ofTest<int> t;).