/** ** File : array.h ** Description: Array template declaration **/ #ifndef Array_h #define Array_h #define ForIndex(i,n) for(int i=0; i<(n); ++i) #define EndFor // for PArray, like Array, T must have a public operator=() template class PArray { private: int size; // must come before a T* a; int n; T pa[psize]; private: void resize(int nsize); void resize_aux(int ne); public: inline PArray(int ne=0) { if (ne <= psize) { size = psize; a = pa; } else { size = ne; a = new T[ne]; } n=ne; } PArray& operator=(const PArray& ar); PArray(const PArray& ar); inline ~PArray() { if (size!=psize) delete[] a; } inline int num() const { return n; } inline void clearcompletely() { if (size != psize) { delete[] a; size = psize; a = pa; } n=0; } /* * allocate ne, CLEAR if too small */ inline void init(int ne) { if (ne > size) { if (size!=psize) delete[] a; size=ne; a=new T[ne]; } n=ne; } /* * allocate at least e+1, COPY if too small */ inline void access(int e) { int ne=e+1; if (ne>size) resize_aux(ne); if (ne>n) n=ne; } /* * allocate ne, COPY if too small */ inline void need(int ne) { if (ne>size) resize_aux(ne); n=ne; } /* * ret: previous num() */ inline int add(int ne) { int cn=n; need(n+ne); return cn; } inline void sub(int ne) { n-=ne; } /* * do not use a+=a[..]!! * add() may allocate a[]!! */ inline PArray& operator+=(const T& e) { int i=add(1); a[i]=e; return *this; } inline void squeeze() { if (n=0 && i PArray& PArray::operator=(const PArray& ar) { if (&ar==this) return *this; init(ar.num()); ForIndex(i,n) { a[i]=ar[i]; } EndFor; return *this; } template PARRAY_INLINE PArray::PArray(const PArray& ar) : size(psize), a(pa), n(0) { *this=ar; } template void PArray::resize(int nsize) { T* na; if (nsize<=psize) { if (size==psize) return; na=pa; } else { na=new T[nsize]; } ForIndex(i,n) { na[i]=a[i]; } EndFor; if (size!=psize) delete[] a; a=na; size=nsize<=psize?psize:nsize; } template void PArray::resize_aux(int ne) { resize(max(int(n*1.5f)+3,ne)); } template PARRAY_INLINE int PArray::contains(const T& e) const { ForIndex(i,n) { if (a[i]==e) return 1; } EndFor; return 0; } template PARRAY_INLINE int PArray::index(const T& e) const { ForIndex(i,n) { if (a[i]==e) return i; } EndFor; assertnever(""); return 0; } #endif //Array_h