35657

Untitled

Oct 21st, 2023
790
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1.  
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. class Vector {
  8. public:
  9.     Vector() {
  10.         arr = new int[4];
  11.         size = 0;
  12.         capacity = 4;
  13.     }
  14.  
  15.     void push_back(const int value) {
  16.         check_capacity();
  17.         arr[size] = value;
  18.         size++;
  19.     }
  20.  
  21.     void insert(const int index, const int value) {
  22.         if (index < 0 || index >= size) {
  23.             cout << "Invalid index" << endl;
  24.             return;
  25.         }
  26.         check_capacity();
  27.         for (int i = size; i > index; i--) {
  28.             arr[i] = arr[i - 1];
  29.         }
  30.         arr[index] = value;
  31.         size++;
  32.     }
  33.  
  34.     void erase(const int index) {
  35.  
  36.     }
  37.  
  38.     void pop_back() {
  39.         size--;
  40.     }
  41.  
  42.     void print() {
  43.         for (int i = 0; i < size; i++) {
  44.             cout << arr[i] << " ";
  45.         }
  46.         cout << endl;
  47.     }
  48.  
  49. private:
  50.     int* arr; // массив для хранения элементов
  51.     int size; // текущее количество элементов в массиве
  52.     int capacity; // вместимость (емкость) массива
  53.  
  54.     void check_capacity() {
  55.         if (size == capacity) {
  56.             int* temp = new int[capacity * 2];
  57.             for (int i = 0; i < size; i++) {
  58.                 temp[i] = arr[i];
  59.             }
  60.             delete[] arr;
  61.             arr = temp;
  62.             capacity *= 2;
  63.         }
  64.     }
  65. };
  66.  
  67. void Print(vector<int>& vec) {
  68.     for (int a : vec) {
  69.         cout << a << " ";
  70.     }
  71.     cout << endl;
  72. }
  73.  
  74.  
  75. int main() {
  76.  
  77.     Vector vec2;
  78.     vec2.print();
  79.     vec2.push_back(35);
  80.     vec2.print();
  81.  
  82.     for (int i = 0; i < 10; i++) {
  83.         vec2.push_back(i + 1);
  84.     }
  85.     vec2.print();
  86.  
  87.     vec2.pop_back();
  88.     vec2.print();
  89.     vec2.insert(2, 55);
  90.     vec2.print();
  91. }
  92.  
  93.  
Advertisement
Add Comment
Please, Sign In to add comment