Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly select an element from an enumeration in a type-safe way with newest C++

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?

like image 608
hkBst Avatar asked Nov 27 '16 08:11

hkBst


1 Answers

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';
like image 157
Ray Hamel Avatar answered Nov 09 '22 04:11

Ray Hamel