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

后端 未结 8 1764
礼貌的吻别
礼貌的吻别 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:28

    I posted this solution on a Google+ article where someone else referenced this. Posting it here, as this one is slightly better than others because it avoids bias by using std::uniform_int_distribution:

    #include  
    #include  
    
    template
    Iter select_randomly(Iter start, Iter end, RandomGenerator& g) {
        std::uniform_int_distribution<> dis(0, std::distance(start, end) - 1);
        std::advance(start, dis(g));
        return start;
    }
    
    template
    Iter select_randomly(Iter start, Iter end) {
        static std::random_device rd;
        static std::mt19937 gen(rd());
        return select_randomly(start, end, gen);
    }
    

    Sample use is:

    #include 
    using namespace std;
    
    vector foo;
    /* .... */
    int r = *select_randomly(foo.begin(), foo.end());
    

    I ended up creating a gist with a better design following a similar approach.

提交回复
热议问题