线性表

templatestruct arrayList ;
//templateostream& operator<<(ostream&, const arrayList &);
template
struct  arrayList:public linearList
{
	//constructors,copy cons,distructor
	arrayList(size_t initialCapacity=10);
	arrayList(const arrayList&);
	~arrayList(){ delete[]element; }
	//functions
	void pushback(const T&);
	bool empty()const { return listSize!=0; }
	size_t size()const { return listSize; }
	void erase(size_t theIndex) ;
	int indexOf(const T&theElement)const ;
	void insert(const T& theElement, size_t theIndex) ;
	//void output(ostream& out)const ;
	//access private member
	T* begin()const{ return element; }
	T* end()const{ return element + size(); }
	//operators
	T& operator[](const size_t& theIndex)const{ checkIndex(theIndex); return *(element + theIndex); }
	//ostream& operator<<(ostream& out, const arrayList &arr);
	
protected:
	void checkIndex(size_t theIndex)const;
	void reallocate(size_t size);
	T* element;
	size_t listSize = 0;
	size_t arrayLength=0;
};

//function_defination
template
void arrayList::pushback(const T& theElement){
	if (listSize >= arrayLength)
		reallocate(2 * arrayLength);
	*(element + listSize++) = theElement;
}
template
void arrayList::checkIndex(size_t theIndex)const{
	if (theIndex < 0 || theIndex >= listSize)
		throw "Length error!!";
}

template
void arrayList::erase(size_t theIndex){
	checkIndex(theIndex);
	std::copy(element + theIndex + 1, element + listSize, element + theIndex);
}

template
int arrayList::indexOf(const T&theElement)const{
	size_t t=std::find(element, element + listSize, thElement) - element;
	if (t == listSize)
		return -1;
	else return t;
}

template
void arrayList::insert(const T& theElement, size_t theIndex){
	checkIndex(theIndex);                                                                // unfinished
	std::copy_backward(element + theIndex, element + listSize, element + theIndex + 1);
	*(element + theIndex) = theElement;
}

template                                                                                //protected member
void arrayList::reallocate(size_t size){
	if (size <= arrayLength)throw "reallocate error :length short!";
	auto newSpace = new T[size];
	std::copy(element, element + listSize, newSpace);
	delete[]element;
	element = newSpace;
	arrayLength = size;
}
/*
template
void arrayList::output(ostream& cout)const{
	std::copy(element, element + listSize, std::ostream_iterator(cout, " "));
}
*/
//constructors...
template
arrayList::arrayList(size_t initialCapacity){
	element = new T[initialCapacity];
	listSize = arrayLength = initialCapacity;

}

template
arrayList::arrayList(const arrayList&rightArrayList){
	element = new T[rightArrayList.listSize];
	std::copy(rightArrayList.element, rightArrayList.element + rightArrayList.listSize, element);
	listSize = arrayLength = rightArrayList.listSize;
}

你可能感兴趣的:(线性表)