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.
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.
Using rand() to assign enum enum Color {Red, Green, Blue}; Color color = Color(rand()%3);
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.
How about:
enum my_type {
a, b, c, d,
last
};
void f() {
my_type test = static_cast<my_type>(rand() % last);
}
There is no implicit conversion, but an explicit one will work:
my_type test = my_type(rand() % 10);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With