如何在C++中随机选择枚举类型的值?我想做这样的事情。
enum my_type(A,B,C,D,E,F,G,h,J,V);
my_type test(rand() % 10);但这是非法的..。不存在从int到枚举类型的隐式转换。
发布于 2010-06-08 23:58:45
这样如何:
enum my_type {
a, b, c, d,
last
};
void f() {
my_type test = static_cast<my_type>(rand() % last);
}发布于 2010-06-09 00:03:06
没有隐式转换,但可以使用显式转换:
my_type test = my_type(rand() % 10);发布于 2019-06-24 18:48:36
下面是我最近是如何解决类似问题的。我将其放在一个适当的.cc文件中:
static std::random_device rd;
static std::mt19937 gen(rd());在定义枚举的标头中:
enum Direction
{
N,
E,
S,
W
};
static std::vector<Direction> ALL_DIRECTIONS({Direction::N, Direction::E, Direction::S, Direction::W});并生成一个随机方向:
Direction randDir() {
std::uniform_int_distribution<size_t> dis(0, ALL_DIRECTIONS.size() - 1);
Direction randomDirection = ALL_DIRECTIONS[dis(gen)];
return randomDirection;
}别忘了
#include <random>https://stackoverflow.com/questions/2999012
复制相似问题