简体   繁体   中英

C++ Template Class Dynamic Array of Pointers to Arrays

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.

#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

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