Advertisement
bogolyubskiyalexey

Untitled

Mar 5th, 2021
679
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.14 KB | None | 0 0
  1. template<class T>
  2. class MyVector {
  3. private:
  4.     size_t size_ = 0;
  5.     T* ptr_ = nullptr;
  6.     size_t capacity_ = 0;
  7.  
  8. public:
  9.     MyVector() = default;
  10.     MyVector(const MyVector& other) {
  11.         size_ = other.size_;
  12.         capacity_ = other.size_;
  13.         ptr_ = new T[size_];
  14.         for (size_t i = 0; i < size_; ++i) {
  15.             ptr_[i] = other.ptr_[i];
  16.         }
  17.     }
  18.     ~MyVector() {
  19.         delete[] ptr_;
  20.     }
  21.    
  22.     MyVector& operator+= (const MyVector<T>& other) {
  23.         if (size_ + other.size_ <= capacity_) {
  24.             for (size_t i = 0; i < other.size_; ++i) {
  25.                 ptr_[size_] = other.ptr_[i];
  26.             }
  27.             size_ += other.size_;
  28.         } else {
  29.             capacity_ = size_ + other.size_;
  30.             T* new_ptr = new T[capacity_];
  31.             for (size_t i = 0; i < size_; ++i) {
  32.                 new_ptr[i] = ptr_[i];
  33.             }
  34.             for (size_t i = 0; i < other.size_; ++i) {
  35.                 new_ptr[size_ + i] = other.ptr_[i];
  36.             }
  37.             delete[] ptr_;
  38.             prt_ = new_ptr;
  39.         }
  40.         return *this;
  41.     }
  42.     MyVector operator+ (const MyVector<T>& other) const { // *this + other
  43.         auto temp(*this);
  44.         temp += ootthheerr;
  45.         return temp;
  46.     }
  47.    
  48.     //Matrix<int> a;
  49.     //a += a;
  50.     //[1,2,3] += [3,4,5] => [1,2,3,3,4,5]
  51.    
  52.    
  53.    
  54.     size_t size() const {
  55.         return size_;
  56.     }
  57.     size_t capacity() const {
  58.         return capacity_;
  59.     }
  60.     T& front() {
  61.         return ptr_[0];
  62.     }
  63.     const T& front() const {
  64.         return ptr_[0];
  65.     }
  66.     T& back() {
  67.         return ptr_[size_ - 1];
  68.     }
  69.     const T& back() const {
  70.         return ptr_[size_ - 1];
  71.     }
  72.     void push_back(const T& new_elem) {
  73.         if (size_ + 1 <= capacity_) {
  74.             ptr_[size_++] = new_elem;
  75.         } else {
  76.             capacity_ *= 2;
  77.             T* new_ptr = new T[capacity_];
  78.             for (size_t i = 0; i < size_; ++i) {
  79.                 new_ptr[i] = ptr_[i];
  80.             }
  81.             delete[] ptr_;
  82.             ptr_ = new_ptr;
  83.             ptr[size_++] = new_elem;
  84.         }
  85.     }
  86. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement