I've tried to make an implementation of a std::vector, but it has some bugs that I cannot figure out, for one, the Append (same as push_back) method doesn't work. If anyone could help me to find the bugs that would be appreciated.
template< typename t >
class vector_t{
t *data;
int size;
int max_size;
public:
vector_t( void )
{
data = NULL;
size = 0;
max_size = 0;
}
vector_t( int sz )
{
data = NULL;
size = 0;
max_size = 0;
Allocate( sz );
}
vector_t( int sz, const t &value )
{
data = NULL;
size = 0;
max_size = 0;
Allocate( sz );
Set( value );
}
t &operator[]( int i )
{
DEBUG_BREAK_IF( i < 0 || i > size );
return data[i];
}
void Allocate( int sz )
{
if( !data )
{
data = new t[ sz ];
size = sz;
max_size = sz;
Set( t( ) );
return;
}
if( sz < max_size ) // never shrink
return;
t *old = data;
data = new t[ sz ];
Q_memcpy( data, old, sizeof( old ) );
size = sz;
max_size = sz;
Set( t( ) );
delete[] data;
}
void Set( const t &value )
{
for( int i = 0; i < size; i++ )
data[i] = value;
}
void Append( const t &val )
{
if( size >= max_size )
Allocate( size + 1 );
data[size-1] = val;
size++;
}
bool Remove( const t &val, bool dealloc = false )
{
bool found = false;
for( int i = 0; i < size; i++ )
{
if( !found )
{
if( data[i] == val )
{
found = true;
if( dealloc )
delete &data[i];
}
}
data[i+1] = data[i];
}
return found;
}
int Count( void )
{
return size;
}
int Allocated( void )
{
return max_size;
}
t *Base( void )
{
return data;
}
t &Front( void )
{
return data[size-1];
}
t &Back( void )
{
return data[0];
}
bool IsEmpty( void )
{
return size == 0;
}
};