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

后端 未结 6 1330
北荒
北荒 2020-11-30 09:26

How can I select a random element in an std::set?

I naively tried this:

int GetSample(const std::set& s) {
  double r =          


        
6条回答
  •  北海茫月
    2020-11-30 10:22

    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;
    }
    

提交回复
热议问题