Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I save and use different functions in C++?

At my course we are getting tasks that always start with filling a random matrix size nxm with random numbers.

I want to create(a library?, a class?) some structure so than any time I want to generate a matrix A I would need just to input the desired size nxm.

In other words, change all this code for something like #include <myrandommatrixgenerator>.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int n, m;

cout << "Enter number of rows (n): ";
cin >> n;
cout << "Enter number of columns (m): ";
cin >> m;

//matrix b with random numbers
srand(time(NULL));

int max = 9, min = -9;

int *b = new int[n*m];
for (int i = 0; i<n; i++)
{
    for (int j = 0; j<m; j++)
    {
        b[i*m + j] = min + ((rand() % max) + 1);
    }
}

//print matrix b
cout << "\nMatrix b:" << endl;

for (int i = 0; i<n; i++)
{
    for (int j = 0; j<m; j++)
    {
        cout << setw(5) << b[i*m + j];
    }
    cout << endl;
}

I do not have a broad overview of the possibilities with C++, so what is the structure that allow me to do that?

>Solution :

Below is an outline of what you can do to achieve that:

  1. Define a class e.g. MyMatrix. A class can encapsulate data and operations related to it. The class can be placed in separate files (h and cpp). A friendly guide: C++ Classes and Objects – w3schooles.
  2. This class should use e.g. a std::vector to hold the data (better than using raw pointers like in your code).
  3. This class should have public methods for getting the metadata (n,m) and data.
  4. This class should have a public method, e.g.: InitRandom(int n, int m), to initialize the MyMatrix object to a matrix size n x m with random values.
  5. In another part of your program you can #include your class h file, and then instantiate a MyMatrix object, and use InitRandom to do what you need.

You can see here a discussion about implementing a matrix class: https://codereview.stackexchange.com/questions/155811/basic-matrix-class-in-c

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading