获得随机元素的容器 - C ++ / STL [英] get random element from container - C++ / STL
问题描述
什么是一个很好的方式来获得一个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.
这篇关于获得随机元素的容器 - C ++ / STL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!