#include #include #include "linearList.h" #include "arrayList.h" template int search(const T& x, const T* arr, int n, int length) { if (n >= length) return -1; if (arr[n] == x) return n; return search(x, arr, n + 1 , length); } template arrayList::arrayList(int initialCapacity) { if (initialCapacity < 1) { std::cout << "Initial Capacity Must Be > 0" << std::endl; //¿¼ÂÇthrow exception } element = new T[initialCapacity]; listSize = 0; } template arrayList::arrayList(const arrayList& theList) { //É±´ arrayLength = theList.arrayLength; listSize = theList.listSize; element = new T[arrayLength]; for (int i = 0; i < listSize; i++) { element[i] = theList.element[i]; } } template arrayList::~arrayList() { delete [] element; } template int arrayList::capacity() { return arrayLength; } template bool arrayList::empty() const { //If empty, return true; if (listSize == 0) return true; return false; } template int arrayList::size() const { //Return Array Size return listSize; } template T& arrayList::get(int theIndex) const { // Return Arr[theIndex] if (theIndex < 0 || theIndex >= listSize) { throw std::out_of_range("Index out of bounds: " + std::to_string(theIndex)); } return element[theIndex]; } template int arrayList::indexOf(const T& theElement) const { //Return the index of "theElement" first appeared return search(theElement, element, 0, listSize); } template T* arrayList::changeLength(T* x, int oldlength, int newlength) { //Arr length altered if (newlength < 0) { throw std::invalid_argument("newlength must be non-negative: " + std::to_string(newlength)); } T* tmp = new T[newlength]; int min = std::min(newlength, oldlength); for (int i = 0; i < min; i++) { tmp[i] = x[i]; } delete[] x; return tmp; } template void arrayList::erase(int theIndex) { //Erase Arr[theIndex] , remember to move the rest if (theIndex < 0 || theIndex >= listSize) { throw std::out_of_range("Index out of bounds: " + std::to_string(theIndex)); } for (int i = theIndex; i < listSize - 1; i++) { element[i] = element[i + 1]; } listSize--; element[listSize] = T(); } template void arrayList::insert(int theIndex, const T& theElement) { //Insert theElement to place Arr[theIndex] if (theIndex < 0 || theIndex > listSize) { throw std::out_of_range("Index out of bounds: " + std::to_string(theIndex)); } if (listSize == arrayLength) { element = changeLength(element, arrayLength, arrayLength + 1); arrayLength++; } for (int i = listSize - 1; i >= theIndex; --i) { element[i + 1] = element[i]; } element[theIndex] = theElement; listSize++; } template void arrayList::output() const { // output into ostream for (int i = 0; i < listSize; i++) { std::cout << element[i] << " "; } std::cout << std::endl; } template class arrayList; template class arrayList; template class arrayList;