如何在C++中从指定枚举类型中获取随机值?
Hey there! The key thing to note here is that your Color enum has non-consecutive underlying values (red=10, black=3, etc.)—so you can’t just generate a random integer and cast it directly. That’d almost certainly give you an invalid value that isn’t part of your enum definition.
Here’s a reliable, clean way to pick a valid random Color every time:
Step 1: Collect All Valid Enum Values First
First, create a container that holds every valid Color member. This gives us a safe pool of values to choose from:
#include <array> // Define an array with all your Color enum values constexpr std::array<Color, 4> all_colors = {Color::red, Color::black, Color::pink, Color::rainbow};
Step 2: Set Up a Proper Random Number Generator
Skip the outdated rand() function if you can—it’s not great for randomness or cross-platform consistency. Instead, use C++11’s <random> library, which is far more robust:
#include <random> // Initialize the random tools (do this once, not every time you need a random color!) std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dist(0, static_cast<int>(all_colors.size()) - 1);
Step 3: Grab Your Random Color
Now generate a random index and use it to pick from our pre-defined array of valid colors:
Color my_random_color = all_colors[dist(gen)];
Full Working Example
Putting it all together, here’s a complete testable snippet:
#include <array> #include <random> #include <iostream> enum Color { red = 10, black = 3, pink = 6, rainbow=99 }; int main() { // Pool of valid Color values constexpr std::array<Color, 4> all_colors = {Color::red, Color::black, Color::pink, Color::rainbow}; // Initialize random number setup std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dist(0, static_cast<int>(all_colors.size()) - 1); // Get random color Color my_random_color = all_colors[dist(gen)]; // Verify the result switch(my_random_color) { case Color::red: std::cout << "Selected color: Red (underlying value: 10)\n"; break; case Color::black: std::cout << "Selected color: Black (underlying value: 3)\n"; break; case Color::pink: std::cout << "Selected color: Pink (underlying value: 6)\n"; break; case Color::rainbow: std::cout << "Selected color: Rainbow (underlying value: 99)\n"; break; } return 0; }
Quick Notes
- If you add new members to your
Colorenum later, make sure to update theall_colorsarray too—otherwise the new values won’t be included in the random selection pool. - If you’re stuck with an older codebase that can’t use
<random>, you can fall back torand(), but it’s less ideal. Just initialize the seed once withsrand(time(nullptr));, then generate an index likeint idx = rand() % all_colors.size();.
内容的提问来源于stack exchange,提问作者Fractale

