Saturday, 31 August 2013

Container class storing, retrieving and addressing issues

Container class storing, retrieving and addressing issues

I'm having trouble with storing data of template type into a non-STL
container. I need to be able to store an address of a created object,
return it, and then properly address the element stored in it later when
an overloaded operator[] is called on the container object. The following
is the code I have implemented so far.
#ifndef FOO_H
#define FOO_H
#include <assert.h>
template<typename T>
class Foo
{
unsigned capacity, items;
T *elements;
public:
Foo(char * pBuffer, unsigned nBufferSize){ ///====== Constructs the
container from a pre-defined buffer.
elements = new T[nBufferSize];
capacity = nBufferSize;
items = 0;
}
~Foo(){
delete[] elements;
}
// Resizes Container
void Resize()
{
T *elements2 = new T[Capacity()*2];
for (unsigned i=0; i < Capacity(); i++)
elements2[i] = elements[i];
delete[] elements;
elements = elements2;
capacity = Capacity()*2;
}
T * Add(){ ///====== Adds an element to the
container, constructs it and returns it to the caller. ====== Note that
the return address needs to be persistent during the lifetime of the
object.
T Obj;
if (IsFull())
{
Resize();
items++;
}
else{
elements[items] = Obj;
items++;
}
return &elements[items-1];
}
void Remove(T * nIndex){ ///====== Removes an object from
the container.
items--;
T *elements2 = new T[capacity-1];
unsigned location = 0;
for (unsigned i=0; i < Capacity(); i++)
{
T* address = &elements[i];
if (&address == &nIndex) // I know this isn't the right way to
find the location of an incoming object.
// Still trying to figure out the right
way of finding that object in the buffer
based of the pointer being passed in.
{
location = i;
break;
}
}
for (unsigned nBefore=0; nBefore < location; nBefore++)
elements2[nBefore] = elements[nBefore];
for (unsigned nAfter=location+1; nAfter < Capacity(); nAfter++)
elements2[nAfter-1] = elements[nAfter];
delete[] elements;
elements = elements2;
}
unsigned Count() const{ ///====== Number of elements
currently in the container.
return items;
}
unsigned Capacity() const{ ///====== Max number of elements the
container can contain. You can limit the capacity to 65536 elements if
this makes your implementation easier.
return capacity;
}
bool IsEmpty() const{ ///====== Is container empty?
if (items >= 1)
return false;
return true;
}
bool IsFull() const{ ///====== Is container full?
if (items == Capacity())
return true;
return false;
}
T const * operator [] (unsigned nIndex) const{ ///======
Returns the n th element of the container [0..Count -1].
assert(nIndex >= 0 && nIndex < Capacity());
return &elements[nIndex];
}
T * operator [] (unsigned nIndex){ ///======
Returns the n th element of the container [0..Count -1].
assert(nIndex >= 0 && nIndex < Capacity());
return &elements[nIndex];
}
};

No comments:

Post a Comment