获得随机元素的容器 - C ++ / STL容器、元素、STL

2023-09-11 01:48:05 作者:春观夜樱

什么是一个很好的方式来获得一个STL范围内的[伪]随机元素?

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

我能想出的最好的是做的std :: random_shuffle(c.begin(),c.end()),然后把我的随机元素从 c.begin()

The best I can come up with is to do std::random_shuffle(c.begin(), c.end()) and then take my random element from c.begin().

不过,我可能想从一个常数的随机元素容器,否则我可能不希望全面洗牌的成本。

However, I might want a random element from a const container, or I might not want the cost of a full shuffle.

有没有更好的办法?

推荐答案

所有使用的答案这里是不正确的,因为兰特()% ñ会产生偏差结果:想象 RAND_MAX == 5 和元素的个数是4。然后你会得到更多的两倍数0 1比数字2或3。

All the answers using % here are incorrect, since rand() % n will produce biased results: imagine RAND_MAX == 5 and the number of elements is 4. Then you'll get twice more the number 0 and 1 than the numbers 2 or 3.

要做到这一点正确的方法是:

A correct way to do this is:

template <typename I>
I random_element(I begin, I end)
{
    const unsigned long n = std::distance(begin, end);
    const unsigned long divisor = (RAND_MAX + 1) / n;

    unsigned long k;
    do { k = std::rand() / divisor; } while (k >= n);

    return std::advance(begin, k);
}

另一个问题是,的std ::兰特只假定有15个随机位,但我们会忘了这个位置。

Another problem is that std::rand is only assumed to have 15 random bits, but we'll forget about this here.