Advertisement
Guest User

Untitled

a guest
Apr 5th, 2020
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. //#include <bits/stdc++.h>
  2.  
  3. #include <iostream>
  4. #include <stdexcept>
  5.  
  6. class Vector {
  7.     int* arr;
  8.     static int size;
  9.  
  10. public:
  11.     Vector() {
  12.         arr = new int[0];
  13.     }
  14.  
  15.     int numar_elemente() {
  16.         return size;
  17.     }
  18.  
  19.     void insert(int index, int value) {
  20.         if (index > size || index < 0)
  21.             throw std::invalid_argument("Invalid index.");
  22.  
  23.         int newSize = size + 1;
  24.         int* newArr = new int[newSize];
  25.  
  26.         memcpy(newArr, arr, index * sizeof(int));
  27.         memcpy(newArr + index + 1, arr + index, (size - index) * sizeof(int));
  28.  
  29.         newArr[index] = value;
  30.  
  31.         size = newSize;
  32.         delete[] arr;
  33.         arr = newArr;
  34.     }
  35.  
  36.     void remove(int index) {
  37.         if (index > size || index < 0)
  38.             throw std::invalid_argument("Invalid index.");
  39.  
  40.         int newSize = size - 1;
  41.         int* newArr = new int[newSize];
  42.  
  43.         memcpy(newArr, arr, index * sizeof(int));
  44.         memcpy(newArr + index, arr + index + 1, (size - index - 1) * sizeof(int));
  45.  
  46.         size = newSize;
  47.         delete[] arr;
  48.         arr = newArr;
  49.     }
  50.  
  51.     int& operator[](int index)
  52.     {
  53.         if (index > (size - 1) || index < 0)
  54.             throw std::invalid_argument("Invalid index.");
  55.  
  56.         return arr[index];
  57.     }
  58. };
  59.  
  60. int Vector::size = 0;
  61.  
  62. int main() {
  63.     Vector caca;
  64.     caca.insert(0, 1);
  65.     caca.insert(1, 2);
  66.     caca.insert(1, 99);
  67.     std::cout << caca[0] << std::endl;
  68.     caca.remove(0);
  69.     std::cout << caca[0] << std::endl;
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement