avr39ripe

cppDynArrCreateFillAddDeletePrint

Sep 22nd, 2021
598
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3. int* createArr(int size)
  4. {
  5.     return new int[size];
  6. }
  7.  
  8. void deleteArr(int* ptr)
  9. {
  10.     delete[] ptr;
  11. }
  12.  
  13. void printArr(const int* begin, const int* const end)
  14. {
  15.     while (begin != end)
  16.     {
  17.         std::cout << *begin++ << ' ';
  18.     }
  19.     std::cout << '\n';
  20. }
  21.  
  22. void fillArr(int* begin, const int* const end, int start, int stop)
  23. {
  24.     while (begin != end)
  25.     {
  26.         *begin++ = (rand() % (stop - start) + start);
  27.     }
  28. }
  29.  
  30.  
  31. void fillArr(int* begin, const int* const end, int val)
  32. {
  33.     while (begin != end)
  34.     {
  35.         *begin++ = val;
  36.     }
  37. }
  38.  
  39. void fillArr(int* begin, const int* const end)
  40. {
  41.     int val{1};
  42.     while (begin != end)
  43.     {
  44.         *begin++ = val++;
  45.     }
  46. }
  47.  
  48. void addElemArr(int*& arr, int& size, int idx, int newElem = 0)
  49. {
  50.     int* newArr{ new int[size + 1] };
  51.  
  52.     for (int i{ 0 }; i < size; ++i)
  53.     {
  54.         *(newArr + i + (i >= idx)) = *(arr + i);
  55.     }
  56.  
  57.     *(newArr + idx) = newElem;
  58.  
  59.     ++size;
  60.     delete[] arr;
  61.     arr = newArr;
  62. }
  63.  
  64. void addElemEndArr(int*& arr, int& size, int newElem = 0)
  65. {
  66.     addElemArr(arr, size, size, newElem);
  67. }
  68.  
  69. void delElemArr(int*& arr, int& size, int idx)
  70. {
  71.     int* newArr{ new int[--size] };
  72.  
  73.     for (int i{ 0 }; i < size; ++i)
  74.     {
  75.         *(newArr + i ) = *(arr + i + (i >= idx));
  76.     }
  77.  
  78.     delete[] arr;
  79.     arr = newArr;
  80. }
  81.  
  82. void delElemEndArr(int*& arr, int& size)
  83. {
  84.     delElemArr(arr, size, size);
  85. }
  86.  
  87. int main()
  88. {
  89.     int arr1Size{ 10 };
  90.     auto arr1{ createArr(arr1Size) };
  91.     fillArr(arr1, arr1 + arr1Size);
  92.     printArr(arr1, arr1 + arr1Size);
  93.  
  94.     addElemArr(arr1, arr1Size, 5, 33);
  95.     printArr(arr1, arr1 + arr1Size);
  96.  
  97.     delElemArr(arr1, arr1Size, 5);
  98.     printArr(arr1, arr1 + arr1Size);
  99.  
  100.     addElemEndArr(arr1, arr1Size, 42);
  101.     printArr(arr1, arr1 + arr1Size);
  102.  
  103.     delElemEndArr(arr1, arr1Size);
  104.     printArr(arr1, arr1 + arr1Size);
  105.    
  106.     deleteArr(arr1);
  107. }
RAW Paste Data