Advertisement
Stoycho_KK

Untitled

Mar 21st, 2022
949
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 KB | None | 0 0
  1. class vector {
  2. private:
  3.     int* data;
  4.     int size;
  5.     int capacity;
  6.  
  7.     void resize() {
  8.         int newCapacity = 2 * capacity;
  9.  
  10.         int* newData = new int[newCapacity];
  11.  
  12.         for (int i = 0; i < capacity; i++)
  13.             newData[i] = data[i];
  14.  
  15.         delete[] data;
  16.         data = newData;
  17.  
  18.         capacity = newCapacity;
  19.     }
  20.  
  21.     void copy(const vector& other) {
  22.         data = new int[other.getCapacity()];
  23.  
  24.         for (int i = 0; i < other.size; i++)
  25.             data[i] = other.data[i];
  26.  
  27.         size = other.size;
  28.         capacity = other.capacity;
  29.     }
  30.  
  31.     void free() {
  32.         delete[] data;
  33.     }
  34.  
  35. public:
  36.     vector() : data(new int[8]), size(0), capacity(8) {}
  37.  
  38.     vector(const vector& other) {
  39.         copy(other);
  40.     }
  41.  
  42.     vector& operator=(const vector& other) {
  43.         if (this != &other) {
  44.             free();
  45.             copy(other);
  46.         }
  47.         return *this;
  48.     }
  49.  
  50.     int getSize() const {
  51.         return size;
  52.     }
  53.  
  54.     int getCapacity() const {
  55.         return capacity;
  56.     }
  57.  
  58.     void push_back(int& val) {
  59.         if (size == capacity)
  60.             resize();
  61.         data[size++] = val;
  62.     }
  63.  
  64.     int operator[](int arg) const {
  65.         if (arg < 0 || arg >= size)
  66.             throw std::exception("out of bound");
  67.         return data[arg];
  68.     }
  69.  
  70.     ~vector() {
  71.         free();
  72.     }
  73. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement