C++

Створити шаблонний клас-контейнер Array, який
є масивом, що дозволяє зберігати об’єкти заданого типу.
Клас повинен реалізовувати наступніі функції:
■ GetSize — отримання розміру масиву (кількість елементів, під які виділено пам’ять);
■ SetSize (int size, int grow = 1) — щоб вибрати розмір
масиву (якщо параметр size більший за попередній
розмір масиву, то виділяється додатковий блок пам’яті, якщо ні, то «зайві» елементи губляться і пам’ять
звільняється); параметр grow визначає для якої кількості елементів необхідно виділити пам’ять, якщо
кількість елементів є більшою від поточного розміру
масиву. Наприклад, SetSize (5, 5); означає, що під час
додавання 6-го елемента розмір масиву стає рівним
10, під час додавання 11-го — 15 і т.д.;
■ GetUpperBound — отримання останнього допустимого
індексу в масиві. Наприклад, якщо за розміру масиву 10,
ви додаєте до нього 4 елементи, то функція поверне 3;
■ IsEmpty — масив порожній ?;
■ FreeExtra — видалити «зайву» пам’ять (вище останнього допустимого індексу);
■ RemoveAll — видалити всі;
Практичні завдання №12
1
■ GetAt — отримання певного елемента (за індексом);
■ SetAt — встановлення нового значення для певного
елемента (індекс елемента повинен бути меншим за
поточний розмір масиву);
■ operator [] — для реалізації двох попередніх функцій;
■ Add — додавання елемента в масив (за необхідності
масив збільшується на значення grow функції SetSize);
■ Append — «складання» двох масивів;
■ operator =;
■ GetData — отримання адреси масиву з даними;
■ InsertAt — вставлення елемента (-ів) в задану позицію;
■ RemoveAt — видалення елемента (-ів) із заданої позиції.

Ответы

Ответ дал: mashaharaim2
0

Ответ:

Ось простий шаблонний клас-контейнер C++ для вашого завдання:

```cpp

#include <iostream>

template <typename T>

class Array {

private:

T* data;

int size;

int capacity;

int grow;

public:

Array(int initialCapacity = 10, int initialGrow = 1)

: size(0), capacity(initialCapacity), grow(initialGrow) {

data = new T[capacity];

}

~Array() {

delete[] data;

}

int GetSize() const {

return size;

}

void SetSize(int newSize, int newGrow = 1) {

if (newSize > capacity) {

int newCapacity = capacity + (newSize / newGrow + 1) * newGrow;

T* newData = new T[newCapacity];

std::copy(data, data + size, newData);

delete[] data;

data = newData;

capacity = newCapacity;

}

size = newSize;

grow = newGrow;

}

int GetUpperBound() const {

return size - 1;

}

bool IsEmpty() const {

return size == 0;

}

void FreeExtra() {

if (size < capacity) {

T* newData = new T[size];

std::copy(data, data + size, newData);

delete[] data;

data = newData;

capacity = size;

}

}

void RemoveAll() {

delete[] data;

size = 0;

capacity = 0;

data = new T[capacity];

}

T GetAt(int index) const {

if (index >= 0 && index < size) {

return data[index];

} else {

// Handle out-of-bounds access

// For simplicity, returning a default value (you might want to throw an exception)

return T();

}

}

void SetAt(int index, const T& value) {

if (index >= 0 && index < size) {

data[index] = value;

} else {

// Handle out-of-bounds access

// For simplicity, doing nothing (you might want to throw an exception)

}

}

T& operator[](int index) {

// No bounds checking for simplicity, be cautious when using this

return data[index];

}

void Add(const T& value) {

if (size >= capacity) {

SetSize(size + grow);

}

data[size++] = value;

}

void Append(const Array& other) {

int newSize = size + other.size;

SetSize(newSize);

std::copy(other.data, other.data + other.size, data + size);

size = newSize;

}

Array& operator=(const Array& other) {

if (this != &other) {

delete[] data;

size = other.size;

capacity = other.capacity;

grow = other.grow;

data = new T[capacity];

std::copy(other.data, other.data + size, data);

}

return *this;

}

T* GetData() const {

return data;

}

void InsertAt(int index, const T& value) {

if (index >= 0 && index <= size) {

if (size >= capacity) {

SetSize(size + grow);

}

for (int i = size; i > index; --i) {

data[i] = data[i - 1];

}

data[index] = value;

++size;

} else {

// Handle invalid index

// For simplicity, doing nothing (you might want to throw an exception)

}

}

void RemoveAt(int index) {

if (index >= 0 && index < size) {

for (int i = index; i < size - 1; ++i) {

data[i] = data[i + 1];

}

--size;

} else {

// Handle invalid index

// For simplicity, doing nothing (you might want to throw an exception)

}

}

};

int main() {

// Example usage

Array<int> arr;

arr.Add(1);

arr.Add(2);

arr.Add(3);

std::cout << "Array size: " << arr.GetSize() << std::endl;

std::cout << "Element at index 1: " << arr.GetAt(1) << std::endl;

return 0;

}

```

Вас заинтересует