1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
| #include"linearList.h" #include<iostream> using namespace std;
template<class T> class ArrayList :public LinearList<T> { protected: T* element; int arrayLength; int listSize; bool checkIndex(int theIndex) const; void changeLength();
public: ArrayList(int initialCapacity = 10); ArrayList(const ArrayList<T>& theList); ~ArrayList() { delete[] element; }
bool empty() const { return listSize == 0; }
int size() const { return listSize; }
int capacity() const { return arrayLength; }
T& get(int theIndex) const;
int indexOf(const T& theElement) const;
void erase(int theIndex);
void insert(int theIndex, const T& theElement);
void output();
};
template<class T> ArrayList<T>::ArrayList(int initialCapacity) { if (initialCapacity < 1) { cout << "初始化容量必须大于0" << endl; return; } this->arrayLength = initialCapacity; this->element = new T[arrayLength]; listSize = 0; }
template<class T> ArrayList<T>::ArrayList(const ArrayList<T>& theList) { this->arrayLength = theList.arrayLength; this->listSize = theList.listSize; this->element = new T[arrayLength]; copy(theList.element, theList.element + listSize, element); }
template<class T> bool ArrayList<T>::checkIndex(int theIndex) const { bool ret = !(theIndex < 0 || theIndex > listSize); return ret; }
template<class T> T& ArrayList<T>::get(int theIndex) const { if (checkIndex(theIndex)) { return element[theIndex]; } }
template<class T> int ArrayList<T>::indexOf(const T& theElement) const { int theIndex = (int)find(element, element + listSize, theElement); return theIndex == listSize ? -1 : (theIndex-(int)element)/sizeof(T); }
template<class T> void ArrayList<T>::erase(int theIndex) { if (checkIndex(theIndex)) { copy(element + theIndex + 1, element + listSize, element + theIndex); element[--listSize].~T(); } }
template<class T> void ArrayList<T>::changeLength() { T* temp = new T[arrayLength * 2]; copy(element, element + arrayLength, temp); delete[] element; element = temp; arrayLength = 2 * arrayLength; }
template<class T> void ArrayList<T>::insert(int theIndex, const T& theElement) { if (!checkIndex(theIndex)) { cout << "无效索引" << endl; return; } if (listSize == arrayLength) { changeLength(); } copy_backward(element + theIndex, element + listSize, element + listSize + 1); element[theIndex] = theElement; listSize++; }
template<class T> void ArrayList<T>::output() { for (int i = 0; i < listSize; i++) { cout << element[i] << " "; } cout << endl; }
|