Advertisement
alvsjo

arraytemplate cpp

Dec 29th, 2017
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.92 KB | None | 0 0
  1. #ifndef ARRAYTEMPLATE_CPP
  2. #define ARRAYTEMPLATE_CPP
  3. //mora se dodati guard block i za cpp kod ovakve template klase
  4. #include "ArrayTemplate.h"
  5.  
  6. #include <iostream>
  7. using namespace std;
  8.  
  9. template <class T>
  10. ArrayTemplate<T>::ArrayTemplate(int c)
  11. {
  12.     this->cap=c;
  13.     this->br=0;
  14.     this->data = new T[this->cap];
  15. }
  16.  
  17.  
  18. template <class T>
  19. ArrayTemplate<T>::ArrayTemplate(const ArrayTemplate<T>& a)
  20. {
  21.     this->cap=a.cap;
  22.     this->br=a.br;
  23.     this->data = new T[cap];
  24.     for (int i=0;i<cap;i++)
  25.     {
  26.         this->data[i]=a.data[i];
  27.     }
  28. }
  29.  
  30. template <class T>
  31. ArrayTemplate<T>& ArrayTemplate<T>::operator=(const ArrayTemplate<T>& a)
  32. {
  33.     delete [] this->data;
  34.     this->cap=a.cap;
  35.     this->br=a.br;
  36.     this->data = new T[cap];
  37.     for (int i=0;i<cap;i++)
  38.     {
  39.         this->data[i]=a.data[i];
  40.     }
  41. }
  42.  
  43. template <class T>
  44. bool ArrayTemplate<T>::operator==(const ArrayTemplate<T>& a)
  45. {
  46.     if (this->cap != a.cap)
  47.         return false;
  48.        if (this->br != a.br)
  49.         return false;
  50.     for(int i=0;i<this->br;i++)
  51.     {
  52.         if(this->data[i]!= a.data[i])
  53.             return false;
  54.     }
  55.     return true;
  56. }
  57.  
  58. template <class T>
  59. T& ArrayTemplate<T>::operator[](int index)
  60. {
  61.     if ((index <0) || (index >= this->br))
  62.     {
  63.         throw 0;
  64.     }
  65.  
  66.     return this->data[index];
  67. }
  68.  
  69.  
  70. template <class T>
  71. void ArrayTemplate<T>::Dodaj(T newElem)
  72. {
  73.     if(this->br < this->cap)
  74.     {
  75.         this->data[this->br]=newElem;
  76.         this->br++;
  77.     }
  78.     else
  79.     {
  80.         T* newData =new T[this->cap*2];
  81.         for (int i=0;i<this->cap;i++)
  82.         {
  83.             newData[i]=this->data[i];
  84.         }
  85.         delete[] this->data;
  86.         this->data=newData;
  87.         this->cap*=2;
  88.  
  89.          this->data[this->br]=newElem;
  90.         this->br++;
  91.     }
  92. }
  93.  
  94.  
  95.  
  96. template <class T>
  97. ArrayTemplate<T>::~ArrayTemplate()
  98. {
  99.     delete [] this->data;
  100. }
  101.  
  102.  
  103.  
  104.  
  105.  
  106.  
  107.  
  108.  
  109.  
  110. #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement