123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159 |
- #include <iostream>
- #include "Array.h"
- using namespace std;
- class ArrayException {};
- Array::Array(int startCapacity)
- {
- {
- if (startCapacity <= 0)
- {
- capacity = DEFAULT_CAPACITY;
- }
- else
- {
- capacity = startCapacity;
- }
- ptr = new int[capacity];
- }
- }
- Array::Array(const Array& arr)
- {
- ptr = new int[arr.capacity];
- size = arr.size;
- capacity = arr.capacity;
- for (int i = 0; i < size; i++)
- {
- ptr[i] = arr.ptr[i];
- }
- }
- Array::~Array()
- {
- delete[] ptr;
- }
- Array& Array::operator = (const Array& arr)
- {
- if (this == &arr)
- {
- return *this;
- }
- if (capacity != arr.capacity)
- {
- delete[] ptr;
- ptr = new int[arr.capacity];
- capacity = arr.capacity;
- }
- size = arr.size;
- for (int i = 0; i < size; i++)
- {
- ptr[i] = arr.ptr[i];
- }
- return *this;
- }
- int& Array::operator [] (int index)
- {
- if (index >= size || index < 0)
- {
- throw ArrayException();
- cout << "The index is outside the bounds of array" << endl;
- }
- else
- {
- return ptr[index];
- }
- }
- void Array::increaseCapacity(int newCapacity)
- {
- if (newCapacity < capacity * 2) {
- capacity = capacity * 2;
- }
- else {
- capacity = newCapacity;
- }
- int* newPtr = new int[capacity];
- for (int i = 0; i < size; i++)
- {
- newPtr[i] = ptr[i];
- }
- delete[] ptr;
- ptr = newPtr;
- }
- void Array::insert(int elem, int index)
- {
- if (index < 0 || index > size)
- {
- throw ArrayException();
- }
- if (size == capacity)
- {
- increaseCapacity(size + 1);
- }
- for (int j = size - 1; j >= index; j--)
- {
- ptr[j + 1] = ptr[j];
- }
- size++;
- ptr[index] = elem;
- }
- void Array::remove(int index)
- {
- if (index < 0 || index >= size)
- {
- throw ArrayException();
- }
- for (int j = index; j < size - 1; j++)
- {
- ptr[j] = ptr[j + 1];
- }
- ptr[size - 1] = 0;
- size--;
- }
- int Array::getSize() const
- {
- return size;
- }
- ostream& operator <<(ostream& out, const Array& arr)
- {
- out << "Total size: " << arr.size << endl;
- for (int i = 0; i < arr.size; i++)
- {
- out << arr.ptr[i] << endl;
- }
- return out;
- }
|