可能重复:
生成随机枚举
可以说我有以下内容:
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.
如果你们知道不涉及 3 个 if 语句的更好方法,请告诉我。谢谢。