How to get a random element from a C++ container?

后端 未结 8 1805
礼貌的吻别
礼貌的吻别 2020-11-27 15:02

What is a good way to get a [pseudo-]random element from an STL range?

The best I can come up with is to do std::random_shuffle(c.begin(), c.end()) an

8条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 15:21

    If you can't access the size, I think you would want to do the following. It returns the iterator to the random element.

    #include 
    #include 
    
    template  InputIterator 
    random_n(InputIterator first, InputIterator last) {
       typename std::iterator_traits::difference_type distance = 
            std::distance(first, last);
       InputIterator result = first;
       if (distance > 1) {
          // Uses std::rand() naively.  Should replace with more uniform solution. 
          std::advance( result, std::rand() % distance );
       }
       return result;
    }
    // Added in case you want to specify the RNG.  RNG uses same 
    // definition as std::random_shuffle
    template  InputIterator 
    random_n(InputIterator first, InputIterator last, RandomGenerator& rand) {
       typename std::iterator_traits::difference_type distance = 
           std::distance(first, last);
       InputIterator result = first;
       if (distance > 1) {
          std::advance( result, rand(distance) );
       }
       return result;
    }
    

提交回复
热议问题