Professional Documents
Culture Documents
CPP Program To Implement Virtual Functions
CPP Program To Implement Virtual Functions
Code for Program that defines template of vector class that provides modify and multiplication facility in C++ Programming
#include <iostream.h> #include <conio.h> template <class T> class vector { T *arr; int size; public: vector() { arr=NULL; size=0; } vector(int m); vector(T *a,int n); void modify(T value,int index); void multiply(int scalarvalue); void display(); }; template <class T> vector<T> :: vector(int m) { size=m; arr = new T[size]; for(int i=0;i<size;i++) arr[i]=0; } template <class T> vector<T> :: vector(T *a,int n) { size=n; arr = new T[size]; for(int i=0;i<size;i++) arr[i]=a[i]; } template <class T> void vector<T> :: modify(T value,int index) { arr[index]=value; }
template <class T> void vector<T> :: multiply(int scalarvalue) { for(int i=0;i<size;i++) arr[i] = arr[i] * scalarvalue; } template <class T> void vector<T> :: display() { cout<<"("; for(int i=0;i<size;i++) { cout<<arr[i]; if(i!=size-1) cout<<", "; } cout<<")"; } void main() { clrscr(); //Creating Integer Vector.int iarr[]={1,2,3,4,5}; cout << "Integer Values \n"; for(int i=0; i < 5; i++) { cout << "Enter integer value " << i+1 << " : "; cin >> iarr[i]; } vector <int> v1(iarr,5); //Integer array with 5 elements. cout<<"\nInteger Vector : "; v1.display(); cout<<"\n\nModify index 3 with value 15\n"; v1.modify(15,3); //modifying index 3 with value 15. cout<<"After Modification : "; v1.display(); cout<<"\n\nMultiply with scalar value : 10\n"; v1.multiply(10); //Multiply with scalar value 10. cout<<"After Multiplying : "; v1.display(); cout<<"\n\n"; //Creating double Vector.double darr[]={1.1,2.2,3.3,4.4,5.5}; vector <double> v2(darr,5); //Double array with 5 elements. cout<<"\nDouble Vector : "; v2.display(); cout<<"\n\nModify index 0 with value 9.9 \n"; v2.modify(9.9,0); //modifying index 0 with value 9.9. cout<<"After Modification : "; v2.display(); cout<<"\n\nMultiply with scalar value : 10\n"; v2.multiply(10); //Multiply with scalar value 10. cout<<"After Multiplying : "; v2.display(); cout<<"\n\n";
getch();
Output