// Vector class interface. Supports construction with
// initial size (default is 0), automatic destruction,
// access of the current size, aray indexing via[], deep
// copy, and resizing. Index range checking is performed
// unless NO_CHECK is defined.
class ArrayIndexOutOfBoundsException;
template
class Vector
{
public:
explicit Vector( int initSize = 0 )
: theSize( initSize ), theCapacity( initSize )
{
objects = new Object[ theCapacity ];
}
Vector( const Vector& rhs): objects( NULL )
{
operator=( rhs );
}
~Vector()
{
delete [] objects;
}
Object & operator[]( int index )
{
#ifndef NO_CHECK
if( index < 0 || index >= size() )
throw ArrayIndexOutOfBoundsException();
#endif
return objects[ index ];
}
const Object & operator[]( int index ) const
{
#ifndef NO_CHECK
if ( index < 0 || index >= size() )
throw ArrayIndexOutOfBoundsException();
#endif
return objects[ index ];
}
const Vector & operator=( const Vector& rhs );
void resize( int newSize );
void reserve( int newCapacity );
void push_back( const Object & x );
int size() const
{
return theSize;
}
int capacity()const
{
return theCapacity;
}
private:
int theSize;
int theCapacity;
Object * objects;
};
template
const Vector
delete[] objects; // Reclaim old
theSize = rhs.size(); // Copy size
theCapacity = rhs.capacity();
objects = new Object[ capacity() ];
for ( int k = 0; k < size(); k++ )
{
objects[ k ] = rhs.objects[ k ];
}
return *this;
}
template
void Vector
{
if ( theSize == theCapacity )
{
reserve( 2 * theCapacity + 1 );
}
objects[ theSize++ ] = x;
}
template
void Vector
{
if ( newSize > theCapacity )
{
reserve( newSize * 2 );
}
theSize = newSize;
}
template
void Vector
{
Object * oldArray = objects;
int numToCopy = newCapacity < theSize ? newCapacity : theSize;
objects = new Object[ newCapacity ];
for ( int k = 0; k < numToCopy; k++ )
{
objects[ k ] = oldArray[ k ];
}
theSize = numToCopy;
theCapacity = newCapacity;
delete[] oldArray;
}
/*
** implementation of ArrayIndexOutOfBoundsException
*/
class ArrayIndexOutOfBoundsException{
private :
const char * const data;
public:
const char* getMessage(){
return data;
}
ArrayIndexOutOfBoundsException(const char* const msg
= "Array index out of bounds Exception !")
: data(msg){}
};