2

Possible Duplicate:
generating random enums

I'm looking for the best way to select a element from a enum in c++. At start, i thank use a switch, but, i have some big enums and is not efficient, so, i'm trying to use a for each to do it.

To select a fruit element in a enum:

enum FruitType
{
    kApple,
    kOrange,
    kMelon
};

And try this function:

/**
 * R3turn a random fruit
 */
FruitType giveMekRandomFruit()
{
    randNumber = rand % __TOTALFRUITS // Enum total = 3 elements

    for (int& i: FruitType)
    {
           if (randNumber = i)
           {
           CCLog("Random Fruit selected:" + i);
           return i;   // return the number selected

            }
    }
}

Obviously don't work, i have a problem with the syntaxis or the concept, any idea???

Thanks for your time.

Community
  • 1
  • 1
vgonisanz
  • 11,831
  • 13
  • 78
  • 130

1 Answers1

5

If the enum values are contiguous, just take a random integer in the proper range and cast to the enum. Otherwise, make an array of enum values and index with a random integer.

stefaanv
  • 14,072
  • 2
  • 31
  • 53