使用具有唯一随机数的结构数组创建多个对象

creating multiple objects with array of structures having unique random numbers

本文关键字:创建 数组 对象 结构 唯一 随机数      更新时间:2023-10-16

我正在尝试创建不同的对象,每个对象都有一个带有随机值的数字结构数组。编译后,我在每个对象的数组中都得到了相同的数字序列。
有没有办法在数组中创建具有唯一数字序列的不同对象?

    #include <iostream>
    #include <time.h>
    #include <stdlib.h>
    using namespace std;
    struct storeTwoValue
    {
            int x;
            int y;
    };

    class practice{
    public:
    storeTwoValue storageArray[10];
    void valueGenerator()
    {       srand(time(NULL));
            for (int i = 0; i< 10; i++)
            {
                    storageArray[i].x = rand()%10 +1;
                            storageArray[i].y = rand()%7 + 1;
                    }
            }
            void print()
            {
                    cout<<"x"<<"    "<<"y"<<endl;
                    for (int i = 0; i< 10; i++)
                    {
                            cout<<storageArray[i].x <<"     ";
                            cout<< storageArray[i].y << endl;
                    }
                    cout<<endl;
            }
    };
      int main()
    {
            for(int i=0; i<3; i++)
            {       practice A;
                    A.valueGenerator();
                    A.print();
            }
            return 0;
    }

srand()调用移动到 main 中,即只执行一次。
你使用它的方式,每个对象的调用顺序太短,至少如果你在开始时创建/初始化它们。即它们全部初始化,而time(0)给出相同的种子,这意味着伪随机数生成器基本上是重置的(从相同的初始值开始相同的序列(。

要验证这一点,您可以(在移动 srand 调用之前(扩展您的循环。如果花费足够的时间,以便time(0)可靠地具有不同的值,您将看到组中具有相同值但不同组的对象组。

调用srand()应该只执行一次,更频繁地调用它不会提高随机性。