简体   繁体   English

用随机数填充向量

[英]Fill a vector with random numbers

I have a function in a class I'm writing that is just supposed to fill a vector with random numbers. 我正在编写的类中有一个函数,该函数仅应使用随机数填充向量。 For some reason, it only generates the same random number and fills the array with that number, despite using a loop where rand() is called over and over. 由于某种原因,尽管使用了反复遍历rand()的循环,但它仅生成相同的随机数并用该数字填充数组。 I seeded rand with time(0). 我用时间(0)播种了兰德。 I tried placing the seed inside of the loop and it made no difference. 我尝试将种子放入循环中,这没有什么区别。 Here's my function. 这是我的职能。 'array' is actually a vector. “数组”实际上是一个向量。

void fillArray()
   {
      srand(time(0));

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

You could check the state of array. 您可以检查数组的状态。 Perhaps, size () is zero when the call of for is done, in which case nothing is written into array. 也许在完成for的调用时size()为零,在这种情况下,没有任何内容写入数组。 I suggest that you check that first. 我建议您先检查一下。

Moreover, to perform module 200 is not good for randomness. 而且,执行模块200不利于随机性。 I copy a snippet from man page for rand(): 我从手册页复制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)."

The code above is apparently correct to fill a vector with random numbers. 上面的代码显然是正确的,可以用随机数填充向量。 The error was coming from this function in my class: 错误是由我班上的这个函数引起的:

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

It was created to use the vector class's at function, but I originally declared it const which made it return the same index for every loop iteration. 它是使用向量类的at函数创建的,但是我最初将其声明为const,这使得它在每次循环迭代中都返回相同的索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM