Advertisement
avr39ripe

cppDynArrResizeBasic

May 11th, 2021
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  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.  
  49.  
  50. int main()
  51. {
  52.     int arr1Size{ 10 };
  53.     auto arr1{ createArr(arr1Size) };
  54.     fillArr(arr1, arr1 + arr1Size);
  55.     printArr(arr1, arr1 + arr1Size);
  56.  
  57.     // add new element to array tail
  58.     //int* newArr{ createArr(arr1Size + 1) };
  59.     int* newArr{ new int[arr1Size + 1]{} };
  60.  
  61.     // copy old array content to new array
  62.     for (int i{ 0 }; i < arr1Size; ++i)
  63.     {
  64.         newArr[i] = arr1[i];
  65.     }
  66.  
  67.     //deleteArr(arr1);
  68.     delete[] arr1;
  69.     arr1 = newArr;
  70.     ++arr1Size;
  71.     printArr(arr1, arr1 + arr1Size);
  72.  
  73.     // delete element from array tail
  74.     newArr = new int[--arr1Size];
  75.     for (int i{ 0 }; i < arr1Size; ++i)
  76.     {
  77.         newArr[i] = arr1[i];
  78.     }
  79.     delete[] arr1;
  80.     arr1 = newArr;
  81.     printArr(arr1, arr1 + arr1Size);
  82.  
  83.     deleteArr(arr1);
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement