C++ 随机将枚举类型分配给变量
C++ Randomly Assigning an enumerated type to a variable
可能的重复项:
生成随机枚举
假设我有以下内容:
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);
相关文章:
- 何时在函数中声明堆栈分配变量?
- 取消引用指针并立即为其分配变量,导致分段错误
- 在C++中动态分配变量类型
- 在函数 (c++) 中分配变量类型和大小数组
- 无法在命名空间范围内分配变量
- 自我分配变量的定义
- 在 CUDA C++中分配变量 - 无法分配设备变量
- 在 CPP 中动态分配变量的数据类型
- 为什么无法在类主体中分配变量?
- const 类方法是否阻止在类外部分配变量?
- 从文件中分配变量,并使用定界符分配
- 分配指针后,是否可以为指针指向的事物分配变量名称?
- 读取外部文件并在类似xml的输入中分配变量
- 有没有办法在不分配变量的情况下将字符串连接到数字
- 如果使用alloca在内联函数中的堆栈上分配变量,那么在内联函数返回后,其引用是否有效
- 堆分配变量的结构成员对齐
- 包含溢出缓冲区的堆栈分配变量,也称为缓冲区
- 在 GetTransfer 之后,我在帐户 1 收到未分配变量错误。我无法弄清楚我搞砸了什么逻辑错误
- 对动态分配的变量的引用与指向相同动态分配变量的指针
- 在C++中为用户输入分配变量