利用vector实现的基于数组的线型表

其实吧,怎么说呢。基于vector的线型表和基于数组的线型表其实是一个样子的,差别就在于,vector自带的函数功能

强大一点,很多功能都不需要我们自己动手去实现,直接调用vector自带的函数就可以了。其实用vector就很好,如果没有

特别的要求也没必要自己去实现一个

template<class T>
class vectorList:public linearList<T>
{
	public:
	vectorList(int initialCapacity=10);
	vectorList(const vectorList<T>&);
	~vectorList(delete element;)
	
	bool empty() const{return element->empty();}
	int size() const {return (int) element->size();}
	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;
	
	int capacity()const{return (int)element->capacity();}
	
	typedef typename vector<T>::iterator iterator;
	iterator begin() {return element->begin();}
	iterator end() {return element->end();}
	
	protected:
	void checkIndex(int theIndex)const;
	vector<T>*element;
	}	

上面是类定义!

template<class T>
vectorList<T>::vectorList(int initialCapacity)
{
	if(initialCapacity<1)
	{
		ostringstream s;
		s<<"initial Capacity="<<"initialCapacity"<<"Must be>0";
		throw illegalParameterValue(s.str());
	}
	element=new vector<T>;
	element->reserve(initialCapacity);
}
template<class T>
vectorList<T>::vectorList(const vectorList<T>& theList)
{
	element=new vector<T>(*theList.element);
}

上面是构造函数和复制构造函数,大家应该看到了,直接new了一个vector出来,所有的实现都是调用vector的函数来实现,

基本上就是给vector进行了一下伪装,并没有实现vector不具备的其他功能。为了知识的完整性我将这篇实现写下来,毕竟我也在学习。

reserve(int)这个函数的作用就是利用realloc函数改变vector的在大内存,和arraylist里面的重新new一个大点的内存一样的作用。这里注意和resize(int)进行区分,resize()只是改变size的大小,就和arraylist里面的size一样,他们的区别就是arraylist里面size和capacity的区别。


template<class T>
void vectorList<T>::erase(int theIndex)
{
	checkIndex(theIndex);
	element->erase(begin()+theIndex)
}
template<class T>
void vectorList<T>::insert(int theIndex,const T& theElement)
{
	checkIndex(theIndex);
	element->insert(element->begin()+theIndex,theElement);
}
上面是删除和插入的代码,全部应用了vector自带的函数,并且全部使用迭代器代替指针。


猜你喜欢

转载自blog.csdn.net/du_shuang/article/details/81055727