You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中从指定枚举类型中获取随机值?

How to Get a Random Value from Your Color Enum

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 Color enum later, make sure to update the all_colors array 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 to rand(), but it’s less ideal. Just initialize the seed once with srand(time(nullptr));, then generate an index like int idx = rand() % all_colors.size();.

内容的提问来源于stack exchange,提问作者Fractale

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:00:20