0

I am making a templated matrix class in C++. To create this class I am creating an array of pointers, and those pointers point to dynamic arrays.

So far I have:

    template<typename T> class Matrix
    {
    public:
        //constructor
        int **m = new int*[_rows];
        for (int i = 0; i < _rows; i++)
        {
             m[i] = new int[_cols];
        }

        //destructor
        for (int i = 0; i < _rows; i++)
        {
            delete[] m[i]
        }
        delete[] m;
    };

I would also like to create some functions to manipulate this structure. I have seen code similar to this used a lot but I am not seeing how this creates an array that contains pointers to other arrays. The concept is confusing to me and I would just like for someone to clarify to me how I should do what I want to do.

I want the class to be isolated and not have anything to do with the input. It will likely be called on in other code and use my functions to create a matrix structure. Creating an array of pointers is not the confusing part to me, it is making those pointers point to other arrays and the array of pointers increases in size based on how many input entries there are.

Gene
  • 104
  • 15
  • 1
    Make your life easier and just use `std::vector` instead of pointers and raw memory management. – PaulMcKenzie Sep 26 '17 at 02:05
  • Thank you. Conceptually though, is what I am trying to do possible using dynamically allocated arrays? – Gene Sep 26 '17 at 02:14
  • Of course it is possible. How does a vector work internally? It is doing nothing different than what you're trying to do, only safer. Second, is your goal to develop a Matrix class or fiddle around with dynamic array management? If it is to develop a Matrix class, then using a `vector` will allow you to get on with the real work of developing the Matrix class. – PaulMcKenzie Sep 26 '17 at 05:10

1 Answers1

0
#include <iostream>

using namespace std;

template<typename T> class Matrix
{
public:
    Matrix(int row, int col)
    {
        _rows = row;
        _cols = col;
        m = new T*[_rows];
        for (int i = 0; i < _rows; i++)
        {
            m[i] = new T[_cols];
            for(int j=0; j < _cols; j++)
            {
                m[i][j] = i*10 + j;
            }
        }
    }

    ~Matrix()
    {
        for (int i = 0; i < _rows; i++)
        {
            delete[] m[i];
        }
        delete[] m;
    }

    T **m;
    int _rows;
    int _cols;
};

void main()
{
    Matrix<int> a(3,4);

    for(int i=0; i<a._rows; i++)
    {
        for(int j=0; j<a._cols; j++)
        {
            cout << "[" << i << "][" << j << "]" << a.m[i][j] << " ";
        }
        cout << endl;
    }

}

RESULT:

[0][0]0 [0][1]1 [0][2]2 [0][3]3

[1][0]10 [1][1]11 [1][2]12 [1][3]13

[2][0]20 [2][1]21 [2][2]22 [2][3]23

isdsi
  • 16
  • 2