How to select a random element in std::set?

Posted by dehmann on Stack Overflow See other posts from Stack Overflow or by dehmann
Published on 2010-06-16T11:26:11Z Indexed on 2010/06/16 11:32 UTC
Read the original article Hit count: 142

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about c++

Related posts about iterator