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

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

    Take the number of elements, c.size(), then get a random_number between 0 and c.size(), and use:

    auto it = c.begin();
    std::advance(it, random_number)
    

    Have a look at http://www.cplusplus.com/reference/clibrary/cstdlib/rand/

提交回复
热议问题