null_radix
null_radix

Reputation: 702

generating random 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.

Upvotes: 19

Views: 31061

Answers (3)

Bart Louwers
Bart Louwers

Reputation: 932

Here is how I solved a similar problem recently. I put this in an appropiate .cc file:

static std::random_device rd;
static std::mt19937 gen(rd());

Inside the header that defines the enum:

enum Direction
{
    N,
    E,
    S,
    W
};
static std::vector<Direction> ALL_DIRECTIONS({Direction::N, Direction::E, Direction::S, Direction::W});

And to generate a random direction:

Direction randDir() {
    std::uniform_int_distribution<size_t> dis(0, ALL_DIRECTIONS.size() - 1);
    Direction randomDirection = ALL_DIRECTIONS[dis(gen)];
    return randomDirection;
}

Don't forget to

#include <random>

Upvotes: 8

zildjohn01
zildjohn01

Reputation: 11515

How about:

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

void f() {
    my_type test = static_cast<my_type>(rand() % last);
}

Upvotes: 31

Mike Seymour
Mike Seymour

Reputation: 254441

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

my_type test = my_type(rand() % 10);

Upvotes: 9

Related Questions