Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Header file
- #ifndef _H_ARRAY
- #define _H_ARRAY
- class Array
- {
- public:
- Array(); // Default Constructor
- Array(Array& arr); // Assignment Operator
- ~Array(); // Destructor
- // Constants
- const int DEFAULT_SIZE = 10;
- // Public functions
- void pushBack(int value);
- int get(int index) const;
- void remove(int index);
- void removeUnordered(int index);
- int getLength() const;
- bool isEmpty() const { return (_length == 0); }
- void setArrayCapacity(int cap);
- private:
- int* _list; // Holds the array of data
- int _length; // Index indicates size and location items can be added to array
- int _capacity; // Max number of elements that can be stored in the array
- // Private Helper Functions
- void doubleArraySize();
- };
- #endif
- // cpp file
- #include "Array.h"
- #include <iostream>
- Array::Array()
- {
- _list = new int[DEFAULT_SIZE];
- _length = 0;
- _capacity = DEFAULT_SIZE;
- }
- Array::Array(Array& arr)
- {
- _list = new int[arr._capacity];
- for (int i = 0; i < arr._length; i++)
- {
- _list[i] = arr._list[i];
- }
- _capacity = arr._capacity;
- _length = arr._length;
- }
- Array::~Array()
- {
- delete[] _list;
- }
- void Array::pushBack(int value)
- {
- if (_length == _capacity)
- {
- doubleArraySize();
- }
- _list[_length] = value;
- _length++;
- }
- int Array::get(int index) const
- {
- if (index >= 0 && index < _length)
- return _list[index];
- return -1;
- }
- void Array::remove(int index)
- {
- if (index < 0 || index >= _length)
- {
- return;
- }
- for (int i = index; i < _length - 1; i++)
- {
- _list[i] = _list[i + 1];
- }
- _length--;
- }
- void Array::removeUnordered(int index)
- {
- if (index < 0 || index >= _length)
- {
- return;
- }
- _list[index] = _list[_length - 1];
- _length--;
- }
- void Array::setArrayCapacity(int cap)
- {
- if (cap < 1 || cap == _capacity)
- {
- return;
- }
- if (cap >= _length)
- {
- int* temp = new int[cap];
- for (int i = 0; i < _length; i++)
- {
- temp[i] = _list[i];
- }
- delete[] _list;
- _list = temp;
- }
- else
- {
- int* temp = new int[cap];
- for (int i = 0; i < cap; i++)
- {
- temp[i] = _list[i];
- }
- delete[] _list;
- _list = temp;
- _length = cap;
- }
- _capacity = cap;
- }
- int Array::getLength() const
- {
- return _length;
- }
- void Array::doubleArraySize()
- {
- int newCapacity = _capacity * 2;
- int* temp = new int[newCapacity];
- for (int i = 0; i < _length; i++)
- {
- temp[i] = _list[i];
- }
- delete[] _list;
- _list = temp;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement