有没有函数可以获取指定范围内均匀分布的伪随机整数?我可以使用 rand
编写自己的函数,但这似乎是一种很常见的情况,STL 中可能有适合它的东西。
最佳答案
Boost提供了许多随机数生成工具。 对于统一分布,你有这个:
http://www.boost.org/doc/libs/1_49_0/doc/html/boost/random/uniform_real_distribution.html
编辑:更新为包含新的 C++11 实现。对于整数的情况,这里有引用:
http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution
一个简单的例子是:
#include <random>
#include <iostream>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 6);
for(int n=0; n<10; ++n)
std::cout << dis(gen) << ' ';
std::cout << '\n';
}
关于c++ - 在 C++ 中获取均匀分布的随机整数的标准方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10710840/