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

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

    This works fine as long as RAND_MAX is much greater than the container size, otherwise it suffers from the bias problem cited by Alexandre:

    vector::iterator randIt = myvector.begin();
    std::advance(randIt, std::rand() % myvector.size());
    

提交回复
热议问题