[英]Generate Random Number in 2D Vector C++
我正在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 ++代码有什么问题? 预先感谢您的回答。
我认为不应每次都创建生成器,使其成为该成员并仅调用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));
在申请开始时只有一次
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.