Mail Archives: djgpp/1999/04/14/07:55:48
Chris Jones <chris DOT jones AT ucl DOT ac DOT uk> wrote:
> The idea is to increase the size
> of the array ptr by one, so I copy to a dummy array, delete ptr and recreate
> it with a new, larger size. Then copy the old contents across from the dummy
> array and delete it.
This is not very effcient. Suppose you store pointer 'ptr' in your class,
then you can make a copy only once and assign new array pointer
to your class pointer.
Here is snip from my Array template - if you are interested, I can send
you whole code separately.
David Stegbauer
----
const int delta = 16; /*allocate space by 'delta' items to avoid unnecessary
resizing*/
template < class T >
class Array
{
public:
Array (int size=0, bool autosize = true);
~Array ();
int resize (int size);
/* and other methods, including operator[], snipped here*/
private:
int _last_used; //last used index, -1 if empty
int _size; //how much _data can be hold (max possible _last_used is one
less
T *_data;
public:
bool _autosize;
};
template < class T >
inline Array<T>::Array (int size=0, bool autosize = true)
:_last_used(-1), _size(size), _data(0), _autosize(autosize)
{
resize(size);
}
template < class T >
Array<T>::~Array()
{
if (_data) delete[]_data;
}
template < class T >
int Array < T > ::resize (int size)
{
if (size == _size)
return _size;
if (size < _last_used+1)
_last_used = size - 1;
size = ((size - 1) / delta + 1) * delta;
T *tmp = new T[size];
T* tmpx = tmp;
for (int i = 0; i < _last_used; ++i)
{
*tmpx++ = *_data++;
}
delete[]_data;
_data = tmp;
int old_capacity = _size;
_size = size;
return old_capacity;
}
- Raw text -