Sunday 23 October 2016

Generic Vector Using Template

/* AIM : Create a class template to represent a generic vector. Include following
member functions:
1]To create the vector.
2]To modify the value of a given element
3]To multiply by a scalar value
4]To display the vector in the form (10,20,30)
*/

#include<iostream>
using namespace std;

template<class T>
class vector
{
T *v;
int size;
public:
vector(int m) // parameterized constructor to create NULL vector
{
v=new T[size=m];
for(int i=0;i<size;i++)
v[i]=0;
}

void create()
{
for(int i=0;i<size;i++)
{
cout<<"v["<<i<<"] = ";
cin>>v[i];
}
}

void modify()
{
int pos;
cout<<"enter position to make changes :";
cin>>pos;
cout<<"Enter new Value :";
cin>>v[pos];
}

void multiply()
{
T sc;
cout<<"Enter scaler Number to multiply with vector : ";
cin>>sc;
for(int i=0;i<size;i++)
v[i]=v[i]*sc;
}

void display()
{
int i;
cout<<"(";
for(i=0;i<size-1;i++)
{
cout<<v[i]<<",";
}
cout<<v[i]<<")\n";
}


};

int main()
{
int size;
cout<<"enter size of vector: ";
cin>>size;
vector<int> vi(size); //creates int vector
vi.create();
vi.display();
vi.modify();
vi.display();
vi.multiply();
vi.display();

}

No comments:

Post a Comment