Advertisement
Guest User

Untitled

a guest
Apr 25th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include <cstdlib>
  4.  
  5. // Реализуйте шаблон SimpleVector
  6. template <typename T>
  7. class SimpleVector {
  8. public:
  9.   SimpleVector() {
  10.     data = nullptr;
  11.     end_ = nullptr;
  12.     current = nullptr;
  13.   }
  14.   explicit SimpleVector(size_t size) {
  15.     data = new T[size];
  16.     current = data;
  17.     end_ = data + size;
  18.   }
  19.   ~SimpleVector() {
  20.     delete[] data;
  21.   }
  22.  
  23.   T& operator[](size_t index) {
  24.     return *(data + index);
  25.   }
  26.  
  27.   T* begin() {
  28.     return (data);
  29.   }
  30.   T* end() {
  31.     return (end_);
  32.   }
  33.  
  34.   size_t Size() const {
  35.     return (end_ - data);
  36.   }
  37.   size_t Capacity() const {
  38.     return (end_ - data);
  39.   }
  40.   void PushBack(const T& value) {
  41.     if (Capacity() == 0) {      //first elem
  42.         data = new T[1];
  43.         end_ = data + 1;
  44.         *data = value;
  45.     } else {
  46.         if (Size() == Capacity()) {
  47.             size_t i = 0;
  48.             current = new T[2 * Capacity()];
  49.             while (data != end_) {
  50.                 *current++ = *data++;
  51.                 i++;            //count elements
  52.             }
  53.             data -= i;          //move to the beginning
  54.             delete[] data;      //remove old data
  55.             data = current - i; //move pointers to the new memory area
  56.             end_ = current;
  57.         }
  58.         data[Size()] = value;
  59.         end_++;
  60.     }
  61.   }
  62.  
  63. private:
  64.   T *data;
  65.   T *end_;
  66.   T *current;
  67. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement