作为一个初学者,我很难做到这件事......我想用随机生成的信息填充这个结构
struct bunny {
bool is_vampire;
std::string name;
std::string color;
char gender;
int age;
int birth_date;
};
例如我想使用枚举
enum colors{white, brown, black, spotted};
当我初始化一些结构时,我会创建一个函数
void struct_fill(bunny x)
{
x.is_vampire = rand()%2;
x.color = colors(rand() % 11);
..... etc.
}
但我认为如果我使用一个数字,它会返回该数字代表的值 /如果假设数字 2 是黑色的/ ...对此有什么简单的解决方案吗?或者用从一定数量的选择中随机选择的数据填充结构的其他方法? *我为我的英语道歉
最佳答案
完成颜色技巧的几种方法。最简单的可能是
std::vector<std::string> colors{"white", "brown", "black", "spotted"};
然后
x.color = colors[rand() % colors.size()];
由于颜色不太可能在运行时改变,std::string
数组(甚至 const char *
)可能更有效。不过,获取尺寸有点棘手。
当我在做的时候,我可以说服你进入giving std::uniform_int_distribution
a read吗?看看它是否比 rand
更适合您?
关于c++ - 填充结构/类时如何获取枚举的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40820591/