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

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

    You can use 0~1 random function to generate a float number for every element in the container as its score. And then select the one with highest score.

提交回复
热议问题