传统的rand()%pool_size方法在一般情况下可以采用,但是实际上这样产生的随机数分布不是完全均匀的。如果对随机数要求较高的话,建议采用下列方法:
#include <random> #include <iostream> const int n=10000; const int k=1000; bool taken[n]; int result[k]; int main() { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(1, n); for(int count=0; count<k; ++count) { int tmpResult = dis(gen); while (taken[tmpResult]) { tmpResult = dis(gen); } result[count] = tmpResult; taken[tmpResult] = true; } for(int count=0; count<k; ++count) std::cout<<result[count]<<std::endl; }
本站所有内容均为互联网搜索引擎提供的公开搜索信息,本站不存储任何数据与内容,任何内容与数据均与本站无关,如有需要请联系相关搜索引擎包括但不限于百度,google,bing,sogou 等
© 2025 tinynews.org All Rights Reserved. 百科问答小站 版权所有