我正在用 C++ 实现一个简单的 2D vector 类,它初始化一个具有给定大小(行数和列数)的 2D vector 以及是否随机化该值。我还实现了将矩阵打印到控制台以查看结果的方法。
我尝试在带有标志“-std=c++17”的 Windows (MSYS2) 中使用 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 vector 。相反,我得到了值都相同的 vector 。
例如。当我在我的电脑上运行代码时,我得到了这个:
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));
仅在申请开始时出现一次
关于c++ - 在二维 vector C++ 中生成随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55453971/