2. Add a new function find(n) for class ArrayList. The function will return the
ID: 3755821 • Letter: 2
Question
2. Add a new function find(n) for class ArrayList. The function will return the position of the first occurrence of n, if the element cannot be found, return 0. Note that in this code the first position in the list is at position I //declaration of the member function int find(ItemType & n); //definition of the member function template int ArrayListeItemType*: : f indlconst ItemType &n) //your code here //hint: use for loop to check each element starting from the //first position of the arrayExplanation / Answer
//C++ program
#include <iostream>
using namespace std;
template <class T>
class ArrayList{
T *arr;
int size;
public:
ArrayList(int n){
arr = new T [n];
size=n;
}
void inputArray(){
cout<<"Enter elements of array ";
for(int i=0;i<size;i++)
cin>>arr[i];
}
int find(T &);
};
template <class T>
int ArrayList<T>::find(T & n){
for(int i=0;i<size ;i++)
if(arr[i]==n)return i+1;
return 0;
}
int main(){
ArrayList<int> a(6);
a.inputArray();
int num;
cout<<"Enter number to find in array : ";
cin>>num;
int position =a.find(num);
if(position==0)cout<<num<<" not found ";
else cout<<num<<" is found at position : "<<position<<" ";
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.