Array.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. #include <iostream>
  2. #include "Array.h"
  3. using namespace std;
  4. class ArrayException {};
  5. Array::Array(int startCapacity)
  6. {
  7. {
  8. if (startCapacity <= 0)
  9. {
  10. capacity = DEFAULT_CAPACITY;
  11. }
  12. else
  13. {
  14. capacity = startCapacity;
  15. }
  16. ptr = new int[capacity];
  17. }
  18. }
  19. Array::Array(const Array& arr)
  20. {
  21. ptr = new int[arr.capacity];
  22. size = arr.size;
  23. capacity = arr.capacity;
  24. for (int i = 0; i < size; i++)
  25. {
  26. ptr[i] = arr.ptr[i];
  27. }
  28. }
  29. Array::~Array()
  30. {
  31. delete[] ptr;
  32. }
  33. Array& Array::operator = (const Array& arr)
  34. {
  35. if (this == &arr)
  36. {
  37. return *this;
  38. }
  39. if (capacity != arr.capacity)
  40. {
  41. delete[] ptr;
  42. ptr = new int[arr.capacity];
  43. capacity = arr.capacity;
  44. }
  45. size = arr.size;
  46. for (int i = 0; i < size; i++)
  47. {
  48. ptr[i] = arr.ptr[i];
  49. }
  50. return *this;
  51. }
  52. int& Array::operator [] (int index)
  53. {
  54. if (index >= size || index < 0)
  55. {
  56. throw ArrayException();
  57. cout << "The index is outside the bounds of array" << endl;
  58. }
  59. else
  60. {
  61. return ptr[index];
  62. }
  63. }
  64. void Array::increaseCapacity(int newCapacity)
  65. {
  66. if (newCapacity < capacity * 2) {
  67. capacity = capacity * 2;
  68. }
  69. else {
  70. capacity = newCapacity;
  71. }
  72. int* newPtr = new int[capacity];
  73. for (int i = 0; i < size; i++)
  74. {
  75. newPtr[i] = ptr[i];
  76. }
  77. delete[] ptr;
  78. ptr = newPtr;
  79. }
  80. void Array::insert(int elem, int index)
  81. {
  82. if (index < 0 || index > size)
  83. {
  84. throw ArrayException();
  85. }
  86. if (size == capacity)
  87. {
  88. increaseCapacity(size + 1);
  89. }
  90. for (int j = size - 1; j >= index; j--)
  91. {
  92. ptr[j + 1] = ptr[j];
  93. }
  94. size++;
  95. ptr[index] = elem;
  96. }
  97. void Array::remove(int index)
  98. {
  99. if (index < 0 || index >= size)
  100. {
  101. throw ArrayException();
  102. }
  103. for (int j = index; j < size - 1; j++)
  104. {
  105. ptr[j] = ptr[j + 1];
  106. }
  107. ptr[size - 1] = 0;
  108. size--;
  109. }
  110. int Array::getSize() const
  111. {
  112. return size;
  113. }
  114. ostream& operator <<(ostream& out, const Array& arr)
  115. {
  116. out << "Total size: " << arr.size << endl;
  117. for (int i = 0; i < arr.size; i++)
  118. {
  119. out << arr.ptr[i] << endl;
  120. }
  121. return out;
  122. }