Advertisement
Guest User

Untitled

a guest
Nov 19th, 2019
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. #include <algorithm>
  2. using namespace std;
  3.  
  4. template <typename T>
  5. class SimpleVector {
  6. public:
  7.     SimpleVector() = default;
  8.     explicit SimpleVector(size_t size) : data(new T[size])
  9.                                         , size(size)
  10.                                         , capacity(size) {}
  11.  
  12.     ~SimpleVector() {
  13.         delete[] data;
  14.     }
  15.  
  16.     T& operator[](size_t index) {
  17.         return data[index];
  18.     }
  19.  
  20.     T* begin() {
  21.         return data;
  22.     }
  23.  
  24.     T* end() {
  25.         return data + size;
  26.     }
  27.  
  28.     [[nodiscard]] size_t Size() const {
  29.         return size;
  30.     }
  31.  
  32.     [[nodiscard]] size_t Capacity() const {
  33.         return capacity;
  34.     }
  35.     void PushBack(const T& value) {
  36.         if (size >= capacity) {
  37.             auto new_cap = capacity == 0 ? 1 : 2 * capacity;
  38.             auto new_data = new T[new_cap];
  39.             copy(begin(), end(), new_data);
  40.             delete[] data;
  41.             data = new_data;
  42.             capacity = new_cap;
  43.         }
  44.         data[size++] = value;
  45.     }
  46.  
  47. private:
  48.     T* data = nullptr;
  49.     size_t size = 0;
  50.     size_t capacity = 0;
  51. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement