What you want to do is to keep the vector the same, but also use a vector of bool, and then wrap that in a class.
Using the vector of bool on decent compiler should be optimized to 1 bit per boolean so that should get rid of your space problem.
class MyNullable {
public:
double value;
bool is_null;
};
class NullableDoubles {
public:
std::vector<double> values;
std::vector<bool> nulls;
void push_back(double d, bool is_null) {
values.push_back(d);
nulls.push_back(is_null);
}
MyNullable GetValue(int index) {
MyNullable result;
result.value = values[index];
result.is_null = nulls[index];
return result;
}
bool IsNull(int index) { return nulls[index]; }
bool MakeNull(int index) { nulls[index] = false; }
};
And I am sure you can see the value(not pun intended) of wrapping that up in a template or two and then making nullable lists of anything.
template <class T>
class NullablesClass {
public:
std::vector<T> values;
std::vector<bool> nulls;
void push_back(T d, bool is_null) {
values.push_back(d);
nulls.push_back(is_null);
}
MyNullable GetValue(int index) {
MyNullableT<T> result;
result.value = values[index];
result.is_null = nulls[index];
return result;
}
bool IsNull(int index) { return nulls[index]; }
bool MakeNull(int index) { nulls[index] = false; }
T GetValue(int index) { return values[index]; }
};
I hope that can do. Seems like the best way to be able to use all possible double values and also know if it is NULL while using the least memory and using the best alignment of memory. The vector is a specialization template in the C++ library so you should really only get 1 bit per bool for that.
std::vector<boost::optional<double>>
is one option.unique_ptr
also is designed to use the heap, wherasboost::optional
is just a value likedouble
itself.