Data Structures, Algorithms, & Applications in C++
Chapter 5, Exercise 17
The code is given below and in the file
arrayListWithRemoveRange.h. Test code is
included in arrayListWithRemoveRange.cpp.
template<class T>
class arrayListWithRemoveRange : public arrayList<T>
{
public:
// constructor and destructor
arrayListWithRemoveRange(int initialCapacity = 10)
: arrayList<T> (initialCapacity) {}
void removeRange(int start, int end);
};
template<class T>
void arrayListWithRemoveRange<T>::removeRange(int start, int end)
{// Remove the elements with index between start and end - 1.
if (start < 0 || end > listSize)
throw illegalIndex();
if (start >= end)
// nothing to remove
return;
// shift elements with higher index
copy(element + end, element + listSize, element + start);
// destroy uneeded elements
int newSize = listSize - end + start;
for (int i = newSize; i < listSize; i++)
element[i].~T();
listSize = newSize;
}
The complexity of the method is O(listSize).