我正在尝试新的方法来生成随机数并将它们填充到一个数组中。到目前为止,我已经完成了。
template<size_t SIZE>
void fill_array(array<int, SIZE>& a)
{
default_random_engine dre;
uniform_int_distribution<int> uid1(0, 1000);
for (int i = 0; i < a.size(); i++)
{
a[i] = uid1(dre);
}
}
我的主文件非常简单,看起来像这样
array<int, 10> a;
Array3 a1;
a1.fill_array(a);
a1.print_array(a);
我以为我每次调试都能得到随机数,但我每次都得到相同的数字。奇怪的是,有时我确实得到了不同的数字,但这是同样的事情,我必须多次调试才能获得新数字。我做错了什么?
最佳答案
即使你使用 std::random_device
不能保证每次都获得不同的序列:
std::random_device may be implemented in terms of an implementation-defined pseudo-random number engine if a non-deterministic source (e.g. a hardware device) is not available to the implementation. In this case each std::random_device object may generate the same number sequence.
例如,在 Windows 上对 stdlibc++ 的旧 g++ 实现发生了这种情况。
此外,由于性能问题,random_device
通常只用于(一次)为伪随机位生成器提供种子,例如 Mersenne twister 引擎 (std::mt19937
)。
您的填充函数可以这样实现:
#include <iostream>
#include <array>
#include <iterator>
#include <random>
#include <algorithm>
template< class Iter >
void fill_with_random_int_values( Iter start, Iter end, int min, int max)
{
static std::random_device rd; // you only need to initialize it once
static std::mt19937 mte(rd()); // this is a relative big object to create
std::uniform_int_distribution<int> dist(min, max);
std::generate(start, end, [&] () { return dist(mte); });
}
int main()
{
std::array<int, 10> a;
fill_with_random_int_values(a.begin(), a.end(), 0, 1000);
for ( int i : a ) std::cout << i << ' ';
std::cout << '\n';
}
现场演示 HERE .
关于c++ - 如何使用 <random> 填充 std::array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41152968/