在C++中,使用标准库中的
一种常见的方法是使用Mersenne Twister引擎生成随机数,例如:
#include <iostream>
#include <random>
int main() {
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<int> dist(1, 100);
for (int i = 0; i < 10; i++) {
std::cout << dist(rng) << std::endl;
}
return 0;
}
在上面的例子中,std::mt19937
是Mersenne Twister引擎,std::random_device{}
用于生成真随机种子,std::uniform_int_distribution
用于生成给定范围内的随机整数。
通过使用这种方法,可以保证生成的随机数具有真随机性。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:c++随机函数如何产生真随机数