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
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.
Create a class that contains three vectors: one for ints, one for doubles, and one that has an entry for each item to tell the type of the corresponding item and its index in the corresponding vector.
If its just a sequence of int
and double
, then you can simply use:
std::vector<double> sequence;
and then insert int
and double
into it. However, this approach doesn't keep track of the type of the items. If the type is critical for you, then probably the following may help you:
struct item
{
union
{
int i;
double d;
} data;
char type; //store 0 for int, 1 for double;
};
std::vector<item> sequence;
Of course, this approach costs you atleast one extra byte per item, for storing the type of the item. You may want to use #pragma pack
techniques to squeeze the extra padding.
Or even better would redesigning your code such that you've two sequences instead of one:
std::vector<int> intSeq;
std::vector<double> doubleSeq;