[英]Optional Variable(variable structure) in structure in c++
I have to implement a data structure in c++, which have optional variable. 我必须在c ++中实现一个具有可选变量的数据结构。 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, eg bool variable has only two states and each state has a meaning for our project. 我不能为变量设置任何默认值来告诉它的可选项,例如bool变量只有两个状态,每个状态对我们的项目都有意义。 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. 我尝试使用
std::vector
但它看起来不太好。
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. 但是对于有点
bool
或4字节的int
创建std::vector
是数据结构的开销。
Can any one suggest out of these methods? 任何人都可以建议这些方法吗?
Some compilers already ship with the upcoming std::optional
- which is called std::experimental::optional
for now. 一些编译器已经附带了即将发布的
std::optional
- 现在称为std::experimental::optional
。 I am already using it for some time now (GCC 4.9+) and it's in good shape. 我已经使用了一段时间了(GCC 4.9+)并且它的状态很好。
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. 如果您的编译器还没有它,但对C ++ 11 / C ++ 14有足够的支持,您也可以使用AndrzejKrzemieński的参考实现中的单个头来避免对Boost的依赖。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.