Class Template – Array
Write a C++ program to create a class template using an array. Perform operations like sorting, searching, and displaying the array using a class template.
A class named Array with the following member variables.
Data TypeVariable NameIntegersizeT*array
Function NameDescriptionvoid sorting() This function is used to sort the array elements in ascending order and display the array.void search(T &search) This function is used to search the array element, if the element is found display "Element found at position x" else print "Element not found"
Sample Input and Output 1:
Menu
1.Sorting integer array
2.Searching array of double values
Enter your choice:
1
Enter size of array:
3
Enter the array elements:
5
2
55
Sorted array
2
5
55
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
template <class T>
class Array{
public:
void sortArray(T arr[],int n){
sort(arr, arr + n);
cout << "\nSorted Array: \n";
for (int i = 0; i < n; ++i)
cout << arr[i] << "\n";
}
void search(double arr[], int n, double x)
{
for (int i = 0; i < n; i++)
if (arr[i] == x)
cout<<"\n"<<x<<" is found at index "<<i<<"\n";
else
cout<<"\n"<<x<<" is not found"<<"\n";
}
};
int main(){
Array <int> a;
Array <double> b;
cout<<"1. Sorting integer array\n2. Searching array of double values";
cout<<"\nEnter your choice:";
int c;
cin>>c;
int n;
if(c==1) {
cout<<"\nEnter size of array:";
cin>>n;
int arr[n];
cout<<"\nEnter the array elements:\n";
for(int i=0;i<n;i++){
cin>>arr[i];
}
a.sortArray(arr,n);
}
if(c==2) {
cout<<"\nEnter size of array:";
cin>>n;
double arr1[n];
cout<<"\nEnter the array elements:\n";
for(int i=0;i<n;i++){
cin>>arr1[i];
}
cout<<"\nEnter element to search: ";
double num;
cin>>num;
b.search(arr1,n,num);
}
return 0;
}
Comments
Leave a comment