用随机数填充向量

Fill a vector with random numbers

本文关键字:向量 填充 随机数      更新时间:2023-10-16

我在我正在编写的类中有一个函数,它应该用随机数填充向量。 出于某种原因,它只生成相同的随机数并用该数字填充数组,尽管使用了一遍又一遍地调用 rand() 的循环。 我用时间(0)播种了兰德。 我尝试将种子放在循环内,但没有区别。 这是我的函数。 "数组"实际上是一个向量。

void fillArray()
   {
      srand(time(0));
      for (unsigned int i = 0; i < array.size(); i++)
      {
         array.at(i) = rand() % 200;
      }
   }

您可以检查数组的状态。也许,当 for 的调用完成时,大小 () 为零,在这种情况下,不会将任何内容写入数组。我建议你先检查一下。

此外,执行模块200不利于随机性。我从 rand() 的手册页复制了一个片段:

In  Numerical Recipes in C: The Art of Scientific Computing (William H.
       Press, Brian P. Flannery, Saul A. Teukolsky, William T. Vetterling; New
       York:  Cambridge University Press, 1992 (2nd ed., p. 277)), the follow-
       ing comments are made:
          "If you want to generate a random integer between 1 and 10,  you
          should always do it by using high-order bits, as in
             j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));
          and never by anything resembling
             j = 1 + (rand() % 10);
          (which uses lower-order bits)."

上面的代码显然是正确的,用随机数填充向量。 错误来自我类中的这个函数:

int at(int index)
   {
      return array.at(index);
   }

创建它是为了使用向量类的 at 函数,但我最初声明它为 const,这使得它为每个循环迭代返回相同的索引。