c++ - uniform_int_distribution using a list instead of a range of values -
i've looked documentation , examples after trying run code unable find method feed list uniform_int_distribution
. not possible then?
does have suggestions on best way randomly pick item given list without using srand()
or rand()
?
you can generate random number in correct range using uniform_int_distribution
, pick element of list using std::next
, like:
#include <algorithm> #include <iostream> #include <list> #include <random> int main() { std::random_device rd; std::mt19937 rng(rd()); std::list<char> lst{'a', 'b', 'c', 'd'}; std::uniform_int_distribution<std::size_t> uid(0, lst.size() - 1); // range [0, size-1] std::size_t pos = uid(rng); // random index in list auto elem = *std::next(lst.begin(), pos); // pick element std::cout << elem << std::endl; // display }