What is a good way to get a [pseudo-]random element from an STL range?
The best I can come up with is to do std::random_shuffle(c.begin(), c.end()) an
If you can't access the size, I think you would want to do the following. It returns the iterator to the random element.
#include
#include
template InputIterator
random_n(InputIterator first, InputIterator last) {
typename std::iterator_traits::difference_type distance =
std::distance(first, last);
InputIterator result = first;
if (distance > 1) {
// Uses std::rand() naively. Should replace with more uniform solution.
std::advance( result, std::rand() % distance );
}
return result;
}
// Added in case you want to specify the RNG. RNG uses same
// definition as std::random_shuffle
template InputIterator
random_n(InputIterator first, InputIterator last, RandomGenerator& rand) {
typename std::iterator_traits::difference_type distance =
std::distance(first, last);
InputIterator result = first;
if (distance > 1) {
std::advance( result, rand(distance) );
}
return result;
}