#ifndef ARRAY_H #define ARRAY_H #include #include #include //#include namespace ecci { template class Array { private: size_t capacity; DataType* data; size_t count; public: Array() : capacity(10) , data(new DataType[capacity]) , count(0) { std::cerr << "Default constructor\n"; assert(data); } // Copy constructor Array(const Array& other) : capacity(other.capacity) , data(new DataType[capacity]) , count(other.count) { std::cerr << "Copy constructor\n"; for ( size_t i = 0; i < count; ++i ) data[i] = other.data[i]; } // Move constructor Array(Array&& other) : capacity(other.capacity) , data(other.data) , count(other.count) { std::cerr << "Move constructor\n"; other.capacity = 0; other.data = nullptr; other.count = 0; } // Copy assignment operator const Array& operator=(const Array& other) { std::cerr << "Copy assignment operator\n"; if ( this != &other ) { if ( capacity != other.capacity ) { delete [] data; capacity = other.capacity; data = new DataType[capacity]; } count = other.count; for ( size_t i = 0; i < count; ++i ) data[i] = other.data[i]; } return *this; } // Move assignment operator const Array& operator=(Array&& other) { std::cerr << "Move assignment operator\n"; if ( this != &other ) { capacity = other.capacity; delete [] data; data = other.data; count = other.count; other.capacity = other.count = 0; other.data = nullptr; } return *this; } ~Array() { std::cerr << "~Destructor\n"; delete [] data; } inline size_t getCount() const { return count; } inline DataType& operator[](size_t pos) { return data[pos]; } inline const DataType& operator[](size_t pos) const { return data[pos]; } bool add(const DataType& value); void print() const; void sort(); private: bool increaseCapacity(); }; template bool Array::add(const DataType& value) { if ( count == capacity ) if ( ! increaseCapacity() ) return false; data[count++] = value; return true; } template void Array::print() const { for (size_t i = 0; i < count; ++i) std::cout << i << ": " << data[i] << std::endl; } template int compare(const void* a, const void* b) { return *(const DataType*)a - *(const DataType*)b; } template void Array::sort() { // qsort(data, count, sizeof(DataType), compare); std::sort(data, data + count); } template bool Array::increaseCapacity() { size_t newCapacity = capacity * 10; DataType* newData = new DataType[newCapacity]; if ( ! newData ) return false; for (size_t i = 0; i < count; ++i ) newData[i] = data[i]; delete [] data; this->data = newData; this->capacity = newCapacity; return true; } } // namespace ecci #endif // ARRAY_H