How can I select a random element in an std::set
?
I naively tried this:
int GetSample(const std::set<int>& s) {
double r = rand() % s.size();
return *(s.begin() + r); // compile error
}
But the operator+
is not allowed in this way.
How can I select a random element in an std::set
?
I naively tried this:
int GetSample(const std::set<int>& s) {
double r = rand() % s.size();
return *(s.begin() + r); // compile error
}
But the operator+
is not allowed in this way.
You could use the std::advance
method.
#include <set>
#include <algorithm>
int main() {
using namespace std;
// generate a set...
set<int> s;
for( int i = 0; i != 10; ++i ) s.insert(i);
set<int>::const_iterator it(s.begin());
// 'advance' the iterator 5 times
advance(it,5);
}
int GetSample(const std::set<int>& s) {
double r = rand() % s.size();
std::set<int>::iterator it = s.begin();
for (; r != 0; r--) it++;
return *it;
}
would be one way of doing it, although not pretty;