tags:

views:

61

answers:

2

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.

+3  A: 

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);
}
xtofl
Oh, I forgot about that method. Thanks, that's exactly what I need.
@dehman: mind, though: it's O(n).
xtofl
Any solution will be O(N). Proof is left as an exercise, hint: how many elements of a std::set can be reached in constant time?
MSalters
A: 
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;

Amir Rachum