Class-matrix with random values
The goal is to create a matrix class that can create two-dimensional arrays of specified sizes, but with random values. The array is created, but I get the same values every time. Please tell me what the problem is?
#include <iostream>
#include <time.h>
#include <iomanip>
using namespace std;
class Matrix
{
private:
int str;
int col;
int **mat;
public:
Matrix(int str, int col) //конструктор класса
{
this -> str = str;
this -> col = col;
mat = new int*[str];
for (int i = 0; i < str; i++)
{
mat[i] = new int[col];
}
cout << "Конструктор " << this << endl;
}
void FillMatrix() //метод заполнения
{
srand(time(NULL));
for (int i = 0; i < str; i++)
{
for (int j = 0; j < col; j++)
{
mat[i][j] = rand() %10;
}
}
}
void PrintMatrix() //вывод
{
for (int i = 0; i < str; i++)
{
for (int j = 0; j < col; j++)
{
cout << setw(4) << mat[i][j];
}
cout << endl;
}
cout << endl;
}
~Matrix() //деструктор, я его должен дописать.
{
delete[]mat;
cout << "Destruct" << this << endl << endl;
}
};
int main()
{
setlocale(LC_ALL, "ru");
Matrix a(3, 3);
Matrix b(3, 3);
b.FillMatrix();
a.FillMatrix();
a.PrintMatrix();
b.PrintMatrix();
}
0
1 answers
For any other value passed through the
seed
parameter, and used when calling thesrand
function, the generation algorithm pseudo-random numbers can generate different numbers with each a subsequent call to therand
function. If you use the same thing the value ofseed
, with each call to the functionrand
, the generation algorithm pseudo-random numbers will generate the same a sequence of numbers.
I would do so:
#include <random>
class Matrix
{
private:
std::mt19937 random_generator_;
std::uniform_int_distribution<std::uint8_t> rand_uid(0, 9);
public:
Matrix() //конструктор класса
{
std::random_device random_device;
random_generator_.seed(random_device());
}
void FillMatrix() //метод заполнения
{
for (int i = 0; i < str; i++)
{
for (int j = 0; j < col; j++)
{
mat[i][j] = rand_uid(random_generator_));
}
}
}
};
0
Author: slippyk, 2018-11-14 12:30:27