Author

Author- Ram Ranjeet Kumar

Wednesday, July 10, 2019

Write A Program In C++ To Implement The Idea Of Template Class.

/* 
           NOTE:- only run on IDE environment
                  like CodeBlock,Visual C,Cfree,DevC++ etc
           Not In Turbo C++
*/

#include<iostream>
#include<conio.h>
using namespace std;

template <class X> class ArrayList
{
private:
struct ControlBlock
{
int capacity;
X *arr;
};
ControlBlock *s;
public:
ArrayList(int capacity1)
{
s=new ControlBlock;
s->capacity=capacity1;
s->arr=new X[s->capacity];
}
void addElement(int index, X data)
{
if(index>=0 && index<=s->capacity)
 s->arr[index]=data;
else
 cout<<"\n Array index is not valid";
}
void viewElement(int index, X data)
{
if(index>=0 && index<=s->capacity)
 data=s->arr[index];
else
 cout<<"\n Array index is not valid";
}
void viewList()
{
int i;
for(i=0;i<s->capacity;i++)
cout<<" "<<s->arr[i];
}
};

int main()
{
int data;
ArrayList <float>list1(4);
list1.addElement(0,9.8);
list1.addElement(1,4.8);
list1.addElement(2,7.9);
list1.addElement(3,3.3);
list1.viewList();
getch();
}

No comments:

Post a Comment