//-------------------------------------------------------------------------- // Template declaration for a flexible array of base type T. // A. Fischer, May 14, 2001 file: flex.hpp // Modified by M. Fischer, October 8, 2009 //=========================================================================== #pragma once #include "tools.hpp" #define FLEX_START 4 // Default length for initial array. //=========================================================================== template class FlexArray { protected:// ------------------------------------------------------------ int maxData; // Current allocation size. int n; // Number of array slots that contain data. T* data; // Pointer to dynamic array of T. private: // -------------------------------------------------------------- void grow(); // Double the allocation length. public: // --------------------------------------------------------------- FlexArray( int ss = FLEX_START ) : maxData(ss), n(0), data( new T[maxData] ) {} ~FlexArray() { if (data != NULL) delete[] data; } int put( T data ); int flexlen() const { return n; } inline T& operator[]( int k ); T* extract() { T* tmp=data; data=NULL; return tmp; } ostream& print( ostream& out ) const{ for (int k=0; k int FlexArray::put( T s ) { if ( n == maxData ) grow(); // Create more space if necessary. data[n] = s; return n++; // Return subscript at which item was stored. } //------------------------------------------- access the kth T in the array. template inline T& FlexArray::operator[]( int k ) { if ( k >= n ) fatal( "Flex_array bounds error." ); return data[k]; // Return reference to desired array slot. } // ------------------------------------- double the allocation length. template void FlexArray::grow() { T* temp = data; // hang onto old data array. maxData>0 ? maxData*=2 : maxData = FLEX_START; data = new T[maxData]; // allocate a bigger one. memcpy(data, temp, n*sizeof(T)); // copy info into new array. delete temp; // recycle (free) old array. // but do not free the things that were contained in it. }