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;
	}
};

Recommended Answers

All 3 Replies

Shouldn't line 75 be assigning to data, not data[size-1]?

Also, what does Q_memcpy do? That's anot a standard function, and you don't include its definition.

it's the same as memcpy. i've been trying to make my code more indepentant, don't ask me why :P

You'd be better off using std::copy than memcpy.

I should point out that there are some fairly subtle problems with your code, in the sense that it often constructs objects with default values and then assigns new values to them. This behavior is often invisible, but does slow things down. It's a bit of a pain to avoid unless you use the allocators and deallocators from the standard library. It's somewhat self-serving to say so, but you can find a detailed description of how to implement vectors in a way that avoids this problem in Accelerated C++.

Anyway, I stand by my implicit claim about the bug in line 75: That isn't just a matter of efficiency; it's a matter of correctness.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.