Advertisement
smatskevich

MyVector

Nov 2nd, 2023
620
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.81 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. // Вектор целых чисел.
  6. class MyVector {
  7.  public:
  8.   int operator[](int i) { return buffer[i]; }
  9.   void PushBack(int x) {
  10.     if (size == capacity) Grow();
  11.     buffer[size++] = x;
  12.   }
  13.   int Size() { return size; }
  14.  private:
  15.   int size = 0;
  16.   int capacity = 0;
  17.   int* buffer = nullptr;
  18.  
  19.   void Grow() {
  20.     int new_capacity = max(capacity * 2, 1);
  21.     int* new_buffer = new int[new_capacity];
  22.     for (int i = 0; i < size; ++i) new_buffer[i] = buffer[i];
  23.     delete[] buffer;
  24.     buffer = new_buffer;
  25.     capacity = new_capacity;
  26.   }
  27. };
  28.  
  29. int main() {
  30.   MyVector v;
  31.   v.PushBack(5);
  32.   v.PushBack(10);
  33.   v.PushBack(11);
  34.   v.PushBack(15);
  35.   v.PushBack(17);
  36.   for (int i = 0; i < v.Size(); ++i)
  37.     cout << v[i] << " ";
  38.   return 0;
  39. }
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement