avr39ripe

cppArrResize

Sep 20th, 2021
38
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3. template <typename T>
  4. void printArr(T* begin, T* end)
  5. {
  6. while (begin != end)
  7. {
  8. std::cout << *begin++ << ' ';
  9. }
  10. std::cout << '\n';
  11. }
  12.  
  13.  
  14. int main()
  15. {
  16. int arrSize{ 10 };
  17. int* arrSrc{ new int[10]{1,2,3,4,5,6,7,8,9,10} };
  18.  
  19. //1,2,3,4,5,6,7,8,9,10
  20. //1,2,3,4,5,[42],6,7,8,9,10
  21. // arrSize == 11
  22.  
  23. printArr(arrSrc, arrSrc + arrSize);
  24.  
  25. auto newArr{ new int[++arrSize] };
  26. for (int i{ 0 }; i < arrSize - 1; ++i)
  27. {
  28. newArr[i] = arrSrc[i];
  29. }
  30. newArr[arrSize - 1] = 11;
  31.  
  32. //delete[] arrSrc;
  33. arrSrc = newArr;
  34.  
  35. printArr(arrSrc, arrSrc + arrSize);
  36.  
  37. newArr = new int[--arrSize];
  38. for (int i{ 0 }; i < arrSize; ++i)
  39. {
  40. newArr[i] = arrSrc[i];
  41. }
  42. //delete[] arrSrc;
  43. arrSrc = newArr;
  44.  
  45. printArr(arrSrc, arrSrc + arrSize);
  46.  
  47. delete[] arrSrc;
  48. return 0;
  49. }
RAW Paste Data