the C++ STL vector has a lot of decent properties, but only works when the size of each item is known at run-time.
I would like to have a vector class that features dynamic item size at run-time.
Background: My items consist of a sequence of integers and doubles; a sequence which is only known at run-time. It would suffice to have the vector be given the size of each item at run-time.
I am aware of possible workarounds, but these tend not to reflect the underlying idea of the algorithm, which is always a bad thing with regards to maintainance. Are there classes which provide such a convenience and work as efficient as one might expect?
EDIT:
This is not about item sizes varying throughout the array. It has nothing to do with that. It is at run-time deciding how large the items in the array are; i.e. a (very) weak form of dynamic typing, in contrast to static typing as used with templates.
Hence the initialization of the object should look like that:
DynamicVector V( lengthofvector, sizeofelement );
An application are simplicial meshes. The object $V$ contains items of fixed size or "type", each consisting of integers for the topological information and doubles for some geometric information. There might even come booleans into play, but this is irrelevant so far.
vector represent a contiguous array in memory. This is efficient, since it can use pointer arithmetics to directly access elements by index. But doing that imply all elements having the same size, and to know this size before building the vector.
For your needs, either use a vector of pointers to elements, of a double linked list. vector of pointers is almost as fast as vector. It only needs one mode deference.
If your integers and doubles are the same size (e.g. 64 bits), you could use an union to access each item either as an integer or as a double. But you'd need a way to know what each element is supposed to be.
The problem is that if you don't have a way to store the size of each item in the vector you'll never be able to get the data back out.
What about just storing ALL the items as
double
? This drastically simplifies things.Alternately you could consider
boost::variant
.EDIT: But really can you explain further why you want to store two different types in the same sequence? That can sometimes indicate that the underlying design needs further thought.
If you don't want to resort to workarounds, I think that you should think about an abstraction of those "dynamic-sized items". It should be designed having in mind that it must be used inside a STL vector (then some requisites have to be guaranteed), such that you can finally write something like: