Advertisement
Guest User

Untitled

a guest
Feb 6th, 2017
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. template <typename T> class ArrayList {
  2. public:
  3.     int capacity_;
  4.     int size_;
  5.     T* data_;
  6.  
  7.  
  8.     ArrayList () : ArrayList(16) {}
  9.  
  10.     explicit ArrayList (int capacity) : capacity_(16), size_(0) {
  11.         while (capacity > capacity_) {
  12.             capacity_ *= 2;
  13.         }
  14.  
  15.         data_ = new T[capacity_];
  16.     }
  17.  
  18.     ArrayList<T> (const ArrayList<T> & that) : capacity_(that.capacity_), size_(that.size_) {
  19.         data_ = new T[capacity_];
  20.         memcpy(data_, that.data_, sizeof(T) * size_);
  21.     }
  22.  
  23.     ArrayList<T> (const ArrayList<T>&& that) : capacity_(that.capacity_), size_(that.size_) {
  24.         data_ = that.data_;
  25.         that.data_ = nullptr;
  26.     }
  27.  
  28.     ~ArrayList() {
  29.         delete[] data_;
  30.     }
  31.  
  32.  
  33.     int size() const {
  34.         return size_;
  35.     }
  36.  
  37.     int capacity() const {
  38.         return capacity_;
  39.     }
  40.  
  41.     void add (T const& value) {
  42.         if (size_ + 1 <= capacity_) {
  43.             data_[size_] = value;
  44.             ++size_;
  45.         }
  46.         else {
  47.             capacity_ *= 2;
  48.  
  49.             T* newData_ = new T[capacity_];
  50.             memcpy(newData_, data_, sizeof(T) * size_);
  51.  
  52.             delete[] data_;
  53.             data_ = newData_;
  54.  
  55.             data_[size_] = value;
  56.             ++size_;
  57.         }
  58.     }
  59.  
  60.  
  61.     T* begin () {
  62.         return data_;
  63.     }
  64.  
  65.  
  66.     T* end () {
  67.         return data_ + size_;
  68.     }
  69.  
  70.  
  71. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement