随机数数组每次都是相同的
Array of random numbers is the same each time
我正在制作一个向量程序,该程序应该每次生成3个不同的向量。
这是我迄今为止的代码:
GenerateVector.h文件:
#ifndef Vector_GenerateVector_h
#define Vector_GenerateVector_h
#endif
#include <string>
#include <sstream>
#include <vector>
using namespace std;
class FourVector
{
int x, y, z, t;
public:
FourVector (int a, int b, int c, int d);
int getX() {return x;}
int getY() {return y;}
int getZ() {return z;}
int getT() {return t;}
};
FourVector::FourVector (int a, int b, int c, int d) {
x = a;
y = b;
z = c;
t = d;
}
string toString(FourVector vec) //get vector function
{
ostringstream s; //making a new string stream
s << "("<< vec.getX() << ", " << vec.getY() << ", " << vec.getZ() << ", " << vec.getT() << ")"; // append to string stream
string combinedString = s.str(); //cast string stream to a string
return combinedString; //return string.
}
FourVector genVector()
{
int x = rand() % 10;
int y = rand() % 10;
int z = rand() % 10;
int t = rand() % 10;
FourVector v (x, y, z, t);
return v;
}
vector<FourVector> createArrayFourVectors()
{
vector<FourVector> vecs; //create array of threevectors.
for (int i = 0; i < 3; i++) {
FourVector v = genVector();
vecs.assign(i, v); // assign threevectors to the array to fill it up.
}
return vecs;
}
main.cpp文件:
#include <iostream>
#include "GenerateVector.h"
using namespace std;
int main(int argc, const char * argv[])
{
int seed = static_cast<int>(time(nullptr));
srand(seed);
vector<FourVector> v = createArrayFourVectors();
for (int i = 0; i < 3; i++) {
FourVector tv = v[i];
cout << toString(tv) << endl;
}
}
(5,1,4,8)
(5,1,4,8)
(0,0,0,0)
程序结束,退出代码为:0
第一个问题是:我不明白为什么只有2个矢量而不是3个。
第二个问题是:为什么矢量1和矢量2总是一样的?我只使用过srand()一次,在我的主函数的开头,但我仍然有这个问题。我认为我的计算机速度太快,无法对时间进行重大更改以生成另一组随机数,但尝试插入usleep(1000000)并没有什么不同。
任何帮助都将不胜感激!
问题出现在vecs.assign(i, v);
中。这种形式的assign
采用一个整数和一个对象,并将向量设置为等于该对象的副本数。在i
上有一个循环,取值为0、1和2,因此在循环的最后一次迭代中,您将设置FourVector
对象的两个副本。这意味着vec
的前两个元素将是相同的副本,并且向量的长度将是2
,并且任何超出该长度的访问尝试都将是未定义的行为。
这是因为未定义的行为。std::vector::assign
函数将替换向量中的现有条目,但向量为空,因此您正在写入向量中不存在的条目。
简单的解决方案?请改用push_back
。
相关文章:
- if数组上的随机数
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 具有随机数的二维数组不会更改
- 如何在 c++ 中从数组中选择一个随机数?
- C++ 用于在数组中打印字符串的随机数
- 如何防止每次 Arduino 启动时颜色数组都是相同的随机数组
- 创建整数的 2D 数组,该数组将使用两个函数用随机数填充矩阵.我做错了什么?
- 需要关于如何将我的随机数数组连接到冒泡排序的帮助
- 如何对0,1,..中的k个随机数进行采样..,n-1,而不缓存到数组
- 使用数组生成随机数
- 测量我的随机数数组打印的时间始终显示为 0 秒
- 数组初始化为所有元素为零,吐出随机数
- 生成随机数并将它们放入数组中
- 如何在C 中创建正常分布式随机数生成器的数组
- 将范围随机数保存到数组而不重复的函数
- 使用具有唯一随机数的结构数组创建多个对象
- 用非重复的随机数填充 2D 数组
- 随机数生成器C++动态数组
- 在多维数组中生成唯一的随机数C++
- 将 2D 数组随机数生成器传递到主C++