// // Typical template dynamic array container class. // By S Melax 1998 // // anyone is free to use, inspect, learn from, or ignore // the code here as they see fit. // // A very simple template array class. // Its easiest to understand this array // class by seeing how it is used in code. // // For example: // for(i=0;i #include template class Array { public: Array(int s=0); Array(Array &array); ~Array(); void allocate(int s); void SetSize(int s); void Pack(); Type& Add(Type); void AddUnique(Type); int Contains(Type); void Insert(Type,int); int IndexOf(Type); void Remove(Type); void DelIndex(int i); Type& DelIndexWithLast(int i); Type * element; int count; int array_size; const Type &operator[](int i) const { assert(i>=0 && i=0 && i ©(const Array &array); Array &operator=(Array &array); }; template Array::Array(int s) { if(s==-1) return; count=0; array_size = 0; element = NULL; if(s) { allocate(s); } } template Array::Array(Array &array) { count=0; array_size = 0; element = NULL; *this = array; } template Array &Array::copy(const Array &array) { assert(array.array_size>=0); count=0; for(int i=0;i Array &Array::operator=( Array &array) { if(array.array_size<0) // negative number means steal the data buffer instead of copying { delete[] element; element = array.element; array_size = -array.array_size; count = array.count; array.count =array.array_size = 0; array.element = NULL; return *this; } count=0; for(int i=0;i Array::~Array() { if (element != NULL && array_size!=0) { delete[] element; } count=0;array_size=0;element=NULL; } template void Array::allocate(int s) { assert(s>0); assert(s>=count); if(s==array_size) return; Type *old = element; array_size =s; element = new Type[array_size]; assert(element); for(int i=0;i void Array::SetSize(int s) { if(s==0) { if(element) { delete[] element; element = NULL; } array_size = s; } else { allocate(s); } count=s; } template void Array::Pack() { allocate(count); } template Type& Array::Add(Type t) { assert(count<=array_size); if(count==array_size) { allocate((array_size)?array_size *2:16); } //int i; //for(i=0;i int Array::Contains(Type t) { int i; int found=0; for(i=0;i void Array::AddUnique(Type t) { if(!Contains(t)) Add(t); } template void Array::DelIndex(int i) { assert(i Type& Array::DelIndexWithLast(int i) { assert(i void Array::Remove(Type t) { int i; for(i=0;i void Array::Insert(Type t,int k) { int i=count; Add(t); // to allocate space while(i>k) { element[i]=element[i-1]; i--; } assert(i==k); element[k]=t; } template int Array::IndexOf(Type t) { int i; for(i=0;i