Advertisement
darkjessy94

template myvector

Feb 24th, 2018
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. #include <cstdlib>
  2.  
  3. #ifndef MYVECTOR_H_INCLUDED
  4. #define MYVECTOR_H_INCLUDED
  5.  
  6. template <class T>
  7. class MyVector
  8. {
  9.     int vsize;
  10.     int maxsize;
  11.     T *array;
  12.     void alloc_new();
  13.     void dealloc();
  14. public:
  15.     MyVector();
  16.     MyVector(int );
  17.     ~MyVector();
  18.     void push_back(T);
  19.     void pop_back();
  20.     int size();
  21.     T operator[](int);
  22.     T& at(int i);
  23. };
  24.  
  25. template<class T>
  26. MyVector<T> :: MyVector()
  27. {
  28.     maxsize=5;
  29.     array=new T[maxsize];
  30.     vsize=0;
  31. }
  32.  
  33. template<class T>
  34. MyVector<T> :: MyVector(int i)
  35. {
  36.     maxsize=i;
  37.     array=new T[maxsize];
  38.     vsize=0;
  39. }
  40.  
  41. template<class T>
  42. MyVector<T> :: ~MyVector()
  43. {
  44.     delete[] array;
  45. }
  46.  
  47. template<class T>
  48. void MyVector<T> :: push_back(T i)
  49. {
  50.     if(vsize+1>maxsize)
  51.         alloc_new();
  52.     array[vsize]=i;
  53.     vsize++;
  54. }
  55.  
  56. template<class T>
  57. T MyVector<T> :: operator[](int i)
  58. {
  59.     return array[i];
  60. }
  61.  
  62. template<class T>
  63. T& MyVector<T> :: at(int i)
  64. {
  65.     if(i<vsize)
  66.         return array[i];
  67.     std::cout<<"Error: Out of range";exit(1);
  68. }
  69.  
  70. template<class T>
  71. void MyVector<T> :: pop_back()
  72. {
  73.     if(vsize>0)
  74.     {
  75.         vsize--;
  76.         dealloc();
  77.     }
  78. }
  79.  
  80. template<class T>
  81. void MyVector<T> :: dealloc()
  82. {
  83.     T* temp;
  84.     temp=new T[vsize];
  85.     for(int i=0;i<vsize;i++)
  86.         temp[i]=array[i];
  87.     delete []array;
  88.     array=temp;
  89. }
  90.  
  91. template<class T>
  92. void MyVector<T> :: alloc_new()
  93. {
  94.     maxsize=vsize*2;
  95.     T *tmp=new T[maxsize];
  96.     for(int i=0;i<vsize;i++)
  97.         tmp[i]=array[i];
  98.     delete[]array;
  99.     array=tmp;
  100. }
  101.  
  102. template<class T>
  103. int MyVector<T> :: size()
  104. {
  105.     return vsize;
  106. }
  107. #endif // MYVECTOR_H_INCLUDED
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement