Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generating random enums

Tags:

c++

enums

How do I randomly select a value for an enum type in C++? I would like to do something like this.

enum my_type(A,B,C,D,E,F,G,h,J,V);
my_type test(rand() % 10);

But this is illegal... there is not an implicit conversion from int to an enum type.

like image 355
null_radix Avatar asked Jun 08 '10 15:06

null_radix


People also ask

How do you generate a random enum?

To allow us to get random value of this BaseColor enum we define a getRandomColor() method in the enum. This method use the java. util. Random to create a random value.

How do you randomize an enum in C++?

Using rand() to assign enum enum Color {Red, Green, Blue}; Color color = Color(rand()%3);

Can you have an ArrayList of enums?

You can create a list that holds enum instances just like you would create a list that holds any other kind of objects: ? List<ExampleEnum> list = new ArrayList<ExampleEnum>(); list.


2 Answers

How about:

enum my_type {
    a, b, c, d,
    last
};

void f() {
    my_type test = static_cast<my_type>(rand() % last);
}
like image 114
zildjohn01 Avatar answered Sep 18 '22 08:09

zildjohn01


There is no implicit conversion, but an explicit one will work:

my_type test = my_type(rand() % 10);
like image 26
Mike Seymour Avatar answered Sep 20 '22 08:09

Mike Seymour