在2D Vector C ++中生成随机数

问题描述 投票:0回答:1

我在C ++中实现了一个简单的2D矢量类,它初始化具有给定大小(行数和列数)的2D矢量以及是否随机化该值。我还实现了将矩阵打印到控制台以查看结果的方法。

我试图在Windows(MSYS2)中使用带有标志“-std = c ++ 17”的GCC 8.3.0来运行代码。这是代码。

#include <random>
#include <iostream>
#include <vector>


class Vec2D
{
public:
    Vec2D(int numRows, int numCols, bool isRandom)
    {
        this->numRows = numRows;
        this->numCols = numCols;

        for(int i = 0; i < numRows; i++) 
        {
            std::vector<double> colValues;

            for(int j = 0; j < numCols; j++) 
            {
                double r = isRandom == true ? this->getRand() : 0.00;
                colValues.push_back(r);
            }

            this->values.push_back(colValues);
        }
    }

    double getRand()
    {
        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_real_distribution<> dis(0,1);

        return dis(gen);
    }

    void printVec2D()
    {
        for(int i = 0; i < this->numRows; i++) 
        {
            for(int j = 0; j < this->numCols; j++)
            {
                std::cout << this->values.at(i).at(j) << "\t";
            }
        std::cout << std::endl;
        }
    }
private:
    int numRows;
    int numCols;

    std::vector< std::vector<double> > values;
};

int main()
{
    Vec2D *v = new Vec2D(3,4,true);

    v->printVec2D();
}

当'isRandom'参数是true时,我期望的是具有随机值的2D矢量。相反,我得到的数值完全相同的向量。例如。当我在计算机中运行代码时,我得到了这个:

0.726249        0.726249        0.726249        0.726249
0.726249        0.726249        0.726249        0.726249
0.726249        0.726249        0.726249        0.726249

我的问题是我的C ++代码有什么问题?提前谢谢您的回答。

c++ vector random printing floating-point
1个回答
1
投票

我认为每次都不应该创建生成器,使这个部分成员只调用dis

    std::random_device rd; //Will be used to ***obtain a seed for the random number engine***
    std::mt19937 gen(rd());
    std::uniform_real_distribution<> dis(0,1);

第二,确保你打电话

std::srand(std::time(nullptr));

只在申请开始时一次

© www.soinside.com 2019 - 2024. All rights reserved.