c++ - 填充结构/类时如何获取枚举的值

标签 c++ struct enums

作为一个初学者,我很难做到这件事......我想用随机生成的信息填充这个结构

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/

相关文章:

c++ - 没有匹配的调用函数

c++ - 如何在运行时优雅地排除代码块

c++ - 我应该在类中使用指向集合的指针吗?

c++ - 错误 : no matching member function for call to 'push_back'

ruby-on-rails - 使用 Rails I18n 翻译 Ruby 枚举符号?

c++ - C++设置进程优先级的方法

c++ - 为什么结构的方法不必在 C++ 中声明?

c - 在 C 怪异行为中使用结构传递数组及其长度

c++ - 如何将用户输入(字符串)映射到枚举值?

python - 使用干净简洁的自动值语法创建 StringAutoEnum 类