重複の可能性:
ランダムな列挙型の生成
私が次のものを持っているとしましょう:
enum Color {
RED, GREEN, BLUE
};
Color foo;
私がやりたいのは、色にfooをランダムに割り当てることです。素朴な方法は次のようになります。
int r = rand() % 3;
if (r == 0)
{
foo = RED;
}
else if (r == 1)
{
foo = GREEN;
}
else
{
foo = BLUE;
}
これを行うためのよりクリーンな方法があるかどうか疑問に思いました。私は次のことを試みました(そして失敗しました):
foo = rand() % 3; //Compiler doesn't like this because foo should be a Color not an int
foo = Color[rand() % 3] //I thought this was worth a shot. Clearly didn't work.
3ifステートメントを含まないより良い方法を知っているかどうか教えてください。ありがとう。