I need to store a collection of ints and doubles (representing nominal and real valued data) in c++. I could obviously store them all in a std::vector<double>
, but this feels a bit wrong and doesn't get the aesthetics bonus points.
I could also cook up something based on polymorphism, but I also need the collection to be really efficient: both storing and retrieving the data in the collection should be as fast as possible. I find it hard to judge whether such a solution would be maximally efficient.
I also found boost::variant, which might be of help here.
Additional info: the number of items in the collection will be small (<100) and known when initializing the collection.
Summarizing: I could obviously solve this in countless ways, but I am unsure what would be a good solution when (i) efficiency is really important and (ii) I also want to write somewhat nice code. What is my best bet here?
Edit, additional info: The collection represents a 'row' in a larger data set, its elements represent the values of certain 'columns'. The properties of the rows are known, so it is known what kind of data is stored at which position. The 'efficiency' I am talking about is primarily the efficiency of retrieving the int/double value of a certain column, although fast setting of values is important too. I have some functions that operate on the data that need to retrieve it as fast as possible. Example:
typedef std::vector<double> Row;
void doubleFun(Row const &row)
{
// Function knows there's always a double at index 0
double value = row[0];
...
}
void integerFun(Row const &row)
{
// Function knows there's always an integer at index 1
int value = row[1];
...
}
After some more thought and reading the suggestions so far, it seems that just storing int columns and double columns in two separate vectors is a solid solution. The collection Row
could then just define two different members for retrieving nominal and real data that the functions can use.
Just storing as a vector<double>
is okay too I guess, but it depends on how fast the conversion between double and int is (which is probably pretty impressive).
Sorry for being a little unclear at first, I hope it's clearer and now and that I can get some more thoughts on the matter.