Reputation: 358
I have to implement a data structure in c++, which have optional variable. As
struct xyz
{
int x; //required
int y; //optional
bool a; // required
bool b; // optional
bool c; // optional
std::string d; //optional
std::string e; // required
........
}
Some of the variables are required means fixed, but some of the variable is optional.
I can't set any default value to the variables to tell its optional, e.g. bool variable has only two states and each state has a meaning for our project. And same for integer as well every value of integer is useful data for me.
I googled but not found any satisfactory answer.
I tried with std::vector
but it not looks good.
struct xyz
{
int x; //required
std::vector<int> y; //optional
bool a; // required
std::vector<bool> b; // optional
........
}
In this method we can check the size of vector, if zero means variable is not present else the variable has the desired value.
But for a bit bool
or 4 byte int
creating a std::vector
is overhead to data structure.
Can any one suggest out of these methods?
Upvotes: 1
Views: 3169
Reputation: 56921
Some compilers already ship with the upcoming std::optional
- which is called std::experimental::optional
for now. I am already using it for some time now (GCC 4.9+) and it's in good shape.
If your compiler does not have it yet but has good-enough support for C++11/C++14, you may also use a single header from Andrzej Krzemieński's reference implementation to avoid the dependency to Boost.
Upvotes: 3