可能重复:
生成随机枚举
可以说我有以下内容:
enum Color {
RED, GREEN, BLUE
};
Color foo;
Run Code Online (Sandbox Code Playgroud)
我想要做的是随机地将foo分配给一种颜色.最直接的方式是:
int r = rand() % 3;
if (r == 0)
{
foo = RED;
}
else if (r == 1)
{
foo = GREEN;
}
else
{
foo = BLUE;
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否有更清洁的方法.我尝试过(并且失败了)以下内容:
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.
Run Code Online (Sandbox Code Playgroud)
如果你们知道任何更好的方式不涉及3 if语句,请告诉我.谢谢.
您可以将int转换为枚举,例如
Color foo = static_cast<Color>(rand() % 3);
Run Code Online (Sandbox Code Playgroud)
作为一种风格问题,您可能希望使代码更加健壮/可读,例如
enum Color {
RED,
GREEN,
BLUE,
NUM_COLORS
};
Color foo = static_cast<Color>(rand() % NUM_COLORS);
Run Code Online (Sandbox Code Playgroud)
这样,如果您Color
在将来的某个时刻添加或删除颜色,代码仍然有效,并且阅读代码的人不必抓住他们的头并想知道文字常量3
来自何处.