⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 array.cpp

📁 主要些了几个最基本的并且是最经典的数据结构算法
💻 CPP
字号:
#include <iostream.h>
#include <stdlib.h>


template<class Type> class Array
{
	public:
		Array(int Size=DefaultSize);
		Array(const Array<Type> &x);
		~Array(){delete []elements;}
		Array<Type> &operator=( Array<Type>&A);//新增加的功能
		Type &operator[](int i);
		Type*operator*()const{return elements;}//新增加的功能
		int Length()const{return ArraySize;}//新增加的功能
		void ReSize(int sz);//新增加的功能
	private:
		Type *elements;
		int ArraySize;
        void getArray();
};

template<class Type> void Array<Type>::getArray()
{
	elements=new Type[ArraySize];
	if(elements==0)
	{
		cerr<<"Memory Allocation error"<<endl;
		ArraySize=0;
		return;
	}
}

template<class Type> Array<Type>::Array(int Size)
{
	if(Size<=0)
	{
		cerr<<"Invalid Array size"<<endl;
		ArraySize=0;
		return;
	}
	ArraySize=Size;
	getArray();
}

template<class Type> Array<Type>::Array(const Array<Type>&x)
{
	int ArraySize=x.Length();
	getArray();
	if(elements==0)
	{
		cerr<<"Memory Allacation Error"<<endl;
		ArraySize=0;
		return;
	}
	Type *scrptr=elements;
	Type *destptr=x.elements;
	while(ArraySize--)
		*scrptr++=*destptr++;
}

template<class Type>  Array<Type> &Array<Type>::operator=( Array<Type>&A)
{
	int ArraySize=A.Length();
	getArray();
	if(elements==0)
	{
		cerr<<"Memorry Allocation Error"<<endl;
		ArraySize=0;
		return *this;
	}
	Type *scrptr=elements;
	Type *destptr=A.elements;
	while(ArraySize--)
		*scrptr++=*destptr++;//为什么需要代替的变量:这可以保证经常需要使用的element变量指针始终是指向首地址
	return *this;
}

template<class Type> Type &Array<Type>::operator [](int i)
{
	if(i<0||i>ArraySize-1)
	{
		cerr<<"Index out of Range"<<endl;
		//return;//有返回值的函数这怎么不可以使用return;来中断函数;又什么可以代替的?
	}
	return elements[i];
}

template<class Type> void Array<Type>::ReSize(int sz)
{
	if(sz<=0) 
		cerr<<"Invalid Array Size"<<endl;
	if(sz!=ArraySize)
	{
		Type *newArray= new Type[sz];
		if(newArray==0)
		{
			cerr<<"Memorry Allocation Error"<<endl;
			return;
		}
		int n=(sz<=ArraySize)?sz:ArraySize;
		Type *scrptr=elements;
		Type *destptr=newArray;
		while(n--)
			*destptr++=*scrptr++;
		delete []elements;//而这里没有使用变量代替时就会有挂掉,因为这里的elements与原来的不相同了,要使elements回到首地址才行
		elements=newArray;
		ArraySize=sz;
		
	}
}


int main()
{
	Array<int> b(5) , c(10);//每次遇到Array变量就会出现"Index out of Range":后来又没有了,可能是编译器的原因
	int n=5;
	while(n--)
		b[n]=n;
	n=5;
	while(n--)
		cout<<b[n]<<"  "<<endl;//endl的作用:1、换行;2、把输出流中数据输出;
	cout<<b.Length()<<endl;
	c.ReSize(5);
	c=b;
	n=5;
	while(n--)
		cout<<b[n]<<"  "<<endl;
	n=5;
	while(n--)
		cout<<c[n]<<"  "<<endl;
	Array<int>d(c);
    n=5;
	while(n--)
		cout<<d[n]<<"  "<<endl;
	return 1;

}





⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -