How can I select a random element in an std::set
?
I naively tried this:
int GetSample(const std::set& s) {
double r =
You could use the std::advance
method.
#include
#include
int main() {
using namespace std;
// generate a set...
set s;
for( int i = 0; i != 10; ++i ) s.insert(i);
auto r = rand() % s.size(); // not _really_ random
auto n = *select_random(s, r);
}
Where
template
auto select_random(const S &s, size_t n) {
auto it = std::begin(s);
// 'advance' the iterator n times
std::advance(it,n);
return it;
}