一。arrayList是一种基于顺序表的stl数据容器;
主要数据成员为指向顺序表地址指针:T* element;
如下全部定义:
template<class T>
class arrayList : public linearList<T>
{
public:
// constructor, copy constructor and destructor
arrayList(int initialCapacity = 10); //初始容量是10
arrayList(const arrayList<T>&);
~arrayList() { delete[] element; }
// ADT methods
bool empty() const { return listSize == 0; }
int size() const { return listSize; }
T& get(int theIndex) const;
int indexOf(const T& theElement) const;
void erase(int theIndex);
void insert(int theIndex, const T& theElement);
void output(ostream& out) const;
// additional method
int capacity() const { return arrayLength; }
protected:
void checkIndex(int theIndex) const;
// throw illegalIndex if theIndex invalid
T* element; // 1D array to hold list elements
int arrayLength; // capacity of the 1D array
int listSize; // number of elements in list
};
二。linearList<T>定义为抽象类(C++风格),具体代码又派生类定义。
三。定义两种构造函数:
1.基于长度构造容器:
template<class T>
arrayList<T>::arrayList(int initialCapacity)
{// Constructor.
if (initialCapacity < 1)
{
ostringstream s;
s << "Initial capacity = " << initialCapacity << " Must be > 0";
throw illegalParameterValue(s.str());
}
arrayLength = initialCapacity;
element = new T[arrayLength];
listSize = 0;
}
2.基于对象copy容器数据结构:
template<class T>
arrayList<T>::arrayList(const arrayList<T>& theList)
{// Copy constructor.
arrayLength = theList.arrayLength;
listSize = theList.listSize;
element = new T[arrayLength];
copy(theList.element, theList.element + listSize, element);
}