随机数数组每次都是相同的

Array of random numbers is the same each time

本文关键字:数组 随机数      更新时间:2023-10-16

我正在制作一个向量程序,该程序应该每次生成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