Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef ARRAY_H
- #define ARRAY_H
- #include <iostream>
- #include <stdexcept>
- using std::cout;
- using std::cin;
- using std::endl;
- using std::ostream;
- template <typename T>
- class Array
- {
- private:
- T* data;
- int length;
- int capacity;
- public:
- void resizeArray()
- {
- T* newArray = new T [capacity * 2];
- for (int i = 0; i < length; i++)
- {
- newArray[i] = data[i];
- }
- delete[] data;
- data = newArray;
- capacity *= 2;
- }
- Array() : length(0), capacity(1)
- {
- data = new T[1];
- }
- Array(const Array& other)
- {
- length = other.length;
- capacity = other.capacity;
- data = new T[other.capacity];
- for (int i = 0; i < length; i++)
- {
- data[i] = other.data[i];
- }
- }
- Array(T arr[], int size)
- {
- data = new T[size];
- length = size;
- capacity = size;
- for (int i = 0; i < size; i++)
- {
- data[i] = arr[i];
- }
- }
- Array(T a, T b)
- {
- data = new T[2];
- data[0] = a;
- data[1] = b;
- length = 2, capacity = 2;
- }
- T& operator[](int index) const
- {
- if (abs(index) > length)
- throw std::overflow_error("Index out of range exception");
- if (index < 0)
- {
- return data[length + index];
- }
- return data[index];
- }
- int size() const
- {
- return length;
- }
- void append(T item)
- {
- if (length >= capacity)
- { resizeArray(); }
- data[length] = item;
- length++;
- }
- Array<T>& operator=(const Array<T>& other)
- {
- if (this != &other)
- {
- delete[] data;
- length = other.size();
- capacity = other.capacity;
- data = new T[capacity];
- for (int i = 0; i < length; i++)
- {
- data[i] = other.data[i];
- }
- }
- return *this;
- }
- friend ostream& operator<<(ostream& out, const Array<T>& arr)
- {
- out << "{";
- for (int i = 0; i < arr.size(); i++)
- {
- out << " ";
- out << arr.data[i];
- }
- out << "}";
- return out;
- }
- ~Array()
- {
- delete[] data;
- }
- };
- #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement