00001
00002 #ifndef _GROW_ARRAY_H_
00003 #define _GROW_ARRAY_H_
00004
00029
00091 template <class T>
00092 class GrowableArray {
00093 private:
00095 typedef enum { StartArraySize = 128 } bogus;
00096
00098 size_t num_elem;
00099
00101 size_t array_size;
00102
00104 T *pArray;
00105
00106 private:
00107
00114 bool twice()
00115 {
00116 bool rslt;
00117
00118 T *old_array = pArray;
00119 size_t new_size = array_size * 2;
00120
00121 pArray = new T [ new_size ];
00122 if (pArray != 0) {
00123 rslt = true;
00124 for (int i = 0; i < array_size; i++) {
00125 pArray[i] = old_array[i];
00126 }
00127
00128 delete [] old_array;
00129
00130 array_size = new_size;
00131 }
00132 else {
00133 rslt = false;
00134 }
00135
00136 return rslt;
00137 }
00138
00139
00140 public:
00141 GrowableArray()
00142 {
00143 pArray = new T[ StartArraySize ];
00144 num_elem = 0;
00145 array_size = StartArraySize;
00146 }
00147
00148 ~GrowableArray()
00149 {
00150 if (pArray != NULL) {
00151 delete [] pArray;
00152 }
00153 }
00154
00156 const size_t length(void) const { return num_elem; }
00157
00159 void set_to_zero()
00160 {
00161 num_elem = 0;
00162 }
00163
00165 T &operator[](const size_t i)
00166 {
00167 assert( i < num_elem );
00168 return pArray[ i ];
00169 }
00170
00172 T operator[](const size_t i ) const
00173 {
00174 assert( i < num_elem );
00175 return pArray[ i ];
00176 }
00177
00179 const T *getData() const { return pArray; }
00180
00182 void append( T item )
00183 {
00184
00185 if (num_elem == array_size) {
00186 bool allocOK = twice();
00187 assert( allocOK );
00188 }
00189
00190 pArray[ num_elem ] = item;
00191 num_elem++;
00192 }
00193
00194
00206 void expand( size_t amount )
00207 {
00208 bool allocOK = true;
00209
00210 while (allocOK && num_elem + amount >= array_size) {
00211 allocOK = twice();
00212 assert( allocOK );
00213 }
00214 num_elem += amount;
00215 }
00216
00217
00219 void remove(void)
00220 {
00221 if (num_elem > 0)
00222 num_elem--;
00223 }
00224
00225 };
00226
00227 #endif