C++ 随机将枚举类型分配给变量

C++ Randomly Assigning an enumerated type to a variable

本文关键字:分配 变量 类型 枚举 随机 C++      更新时间:2023-10-16

可能的重复项:
生成随机枚举

假设我有以下内容:

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 语句的更好方法。谢谢。

你可以只将 int 转换为枚举,例如

Color foo = static_cast<Color>(rand() % 3);

作为风格问题,您可能希望使代码更加健壮/可读,例如

enum Color {        
    RED,
    GREEN,
    BLUE,
    NUM_COLORS
};
Color foo = static_cast<Color>(rand() % NUM_COLORS);

这样,如果您在将来的某个时候向Color添加或删除颜色,代码仍然有效,并且阅读您的代码的人不必挠头并想知道文字常量3来自哪里。

你所需要的只是一个演员阵容:

foo = (Color) (rand() % 3);