Is there a way to randomly select an element from an enumeration in a type-safe way?
The best way to do it, that I could find, is to introduce a terminator value as the last element of the enum, so you know how many values there are, then generate a random integer in the appropriate range that you cast to the enum. But a terminator value does not represent anything, so then you have an invalid enum value, and this is not type-safe. Is there a better way to do it in the latest C++ standards?
This seems like a good use case for a std::map
std::map<std::string, const int> nicer_enum {{"Do", 3}, {"Re", 6}, {"Mi", 9}};
std::cout << nicer_enum["Re"] << '\n'; // 6
auto elem = nicer_enum.cbegin();
std::srand(std::time(nullptr));
std::advance(elem, std::rand() % nicer_enum.size());
std::cout << elem->second << '\n'; // 3, 6 or 9
for (const auto &kv : nicer_enum)
std::cout << kv.first << ": " << kv.second << ' '; // Do: 3 Mi: 9 Re: 6
std::cout << '\n';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With