简体   繁体   中英

Generate Random Number in 2D Vector C++

I am implementing a simple 2D vector class in C++ which initialize a 2D vector with a given size (number of row and column) and whether to randomize the value or not. I also implement the method to print the matrix to the console to see the result.

I have tried to run the code using GCC 8.3.0 in Windows (MSYS2) with flag "-std=c++17". Here is the code.

#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();
}

What I expected is a 2D vector with randomized value when 'isRandom' argument is true . Instead, I got vector with values being all the same. For example. when I run the code in my computer I got this:

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

My question is what is wrong with my C++ code? Thank you in advance for the answer.

I think the generator should not be created each time, make this part member and only call 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);

and second, make sure you called

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

only once at the beging of the application

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM