C++ vector 的简单实现

// 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 &
Vector::operator=( const Vector & rhs )
{
 if ( this == &rhs )
 {
      return *this;
 }

 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::push_back( const Object & x )
{
 if ( theSize == theCapacity )
 {
  reserve( 2 * theCapacity + 1 );
 }

 objects[ theSize++ ] = x;
}

template
void Vector::resize( int newSize )
{
 if ( newSize > theCapacity )
 {
  reserve( newSize * 2 );
 }
 theSize = newSize;
}

template
void Vector::reserve( int newCapacity )
{
 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){}
};

你可能感兴趣的:(C++ vector 的简单实现)