用随机数填充向量
Fill a vector with random numbers
我在我正在编写的类中有一个函数,它应该用随机数填充向量。 出于某种原因,它只生成相同的随机数并用该数字填充数组,尽管使用了一遍又一遍地调用 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,这使得它为每个循环迭代返回相同的索引。
相关文章:
- 用C++中的数字和条件填充向量
- 使用 C++98 标准填充二维静态向量
- 如何使用迭代器填充未知大小的向量?
- 使用 C++-17,如何从字符串向量填充元组
- 用基于范围的for循环填充指针向量
- 使用所述填充构造函数初始化向量中的向量
- 是否有可能让 c++ dll 在后台运行 python 程序并让它填充向量图?如果是这样,如何?
- 如何将目录中的文件属性填充到结构向量中?
- 有没有办法使用数组填充向量?
- 用对对填充向量未按预期工作
- 用于填充 Base 和派生对象的 shared_ptr 向量的函数模板
- 可选类输入中的 C++ 填充向量
- 用构造函数调用填充向量
- DLL – 在 DLL 初始化时填充的静态向量,向客户端程序返回零大小
- 从函数填充的字符串的推导向量到 int 的字符串
- parallel_for lambda 函数填充 2D 向量后出错
- 你能在C++中匿名填充一个向量向量吗?
- 如何有效地用向量填充结构
- 从矢量中擦除元素,并向量填充结构
- 一种用内部向量填充结构向量的优雅/高效方法