Kajm Kajm - 1 year ago 65
C++ Question

How to get value of enums when filling struct/class

I got this quite hard thing to do for me as a beginner... I want to fill this struct with information which would randomly generated

struct bunny {
bool is_vampire;
std::string name;
std::string color;
char gender;
int age;
int birth_date;

I wanted to use enums for example

enum colors{white, brown, black, spotted};

When I would initialize some struct I would make a function

void struct_fill(bunny x)
x.is_vampire = rand()%2;
x.color = colors(rand() % 11);
..... etc.

But I thought that if I use a number it would return value that that number represents
/which in case of lets say number 2 would be black/
... Is there any simple solution to this? Or other way to fill the struct with data randomly chosen from some amount of choices?
*I apologize for my english

Answer Source

Couple ways to do the colour trick. The simplest is probably

std::vector<std::string> colors{"white", "brown", "black", "spotted"};

and then

x.color = colors[rand() % colors.size()];

Since colors is unlikely to change at runtime, an array of std::string (or even const char *) might be more efficient. Bit trickier to get the size, though.

While I'm at it, can I talk you into giving std::uniform_int_distribution a read to see if it's a better fit for you than rand?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download