template<classT> void arrayList<T>::insert(int theIndex, const T& theElement) {// Insert theElement so that its index is theIndex. if (theIndex < 0 || theIndex > listSize) {// invalid index ostringstream s; s << "index = " << theIndex << " size = " << listSize; throwillegalIndex(s.str()); }
// valid index, make sure we have space if (listSize == arrayLength) {// no space, double capacity changeLength1D(element, arrayLength, 2 * arrayLength); arrayLength *= 2; }
// shift elements right one position copy_backward(element + theIndex, element + listSize, element + listSize + 1);
element[theIndex] = theElement;
listSize++; }
不知道各位有没有觉得奇怪,为什么12-16行是当空间不足的时候,数组空间翻倍呢?
同样的问题书上也提供了解答。。。。不过也许是我数学基础太差了,一时半会没理解 😥
本文也参考了Stack Overflow上的Efficiency of growing a dynamic array by a fixed constant each time?