c ++-如何使用< random>填充std :: array [英] c++ - How to use <random> to fill std::array

查看:75
本文介绍了c ++-如何使用< random>填充std :: array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试生成随机数并将其填充到数组中的新方法。到目前为止,我已经完成了。

I am trying new ways to generate random numbers and fill them in an array. So far I have done.

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);

    }

}

我的主文件非常简单,看起来像这样

My main file is very simply and looks like this

    array<int, 10> a;

    Array3 a1;

    a1.fill_array(a);
    a1.print_array(a);

我以为我每次调试都能设法得到随机数,但是每次都能得到相同的数。有时候,我确实得到了不同的数字,这很奇怪,但是同样,我不得不多次调试才能获得新的数字。我做错了什么?

I thought I managed to get random numbers everytime I debug but I get the same numbers everytime. Weird enough sometimes I do get different numbers but then it's the same thing where I have to debug multiple times to get new numbers. What did I do wrong?

推荐答案

即使您使用 std :: random_device 不能保证每次都获得不同的序列:

Even if you use std::random_device there's no guarantee to obtain a different sequence every time:


std :: random_device可以用
实现定义的伪随机数引擎来实现,如果
非确定性来源(例如,硬件设备)不可用于实施。在这种情况下,每个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.

例如,

此外,由于性能问题,通常只使用 random_device (一次)播种伪随机位生成器,例如梅森扭曲器引擎( std :: mt19937 )。

Moreover, due to performace issues, random_device is generally only used (once) to seed a pseudo random bit generator such as the Mersenne twister engine (std::mt19937).

您的填充函数可以这样实现:

Your fill function could be implemented like this:

#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';
}

实时演示这里

这篇关于c ++-如何使用&lt; random&gt;填充std :: array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆