How to create a dynamically new 2D array in C ++

As in the subject, how to create a new 2D array in C ++? This code below does not work very well.

int** t = new *int[3]; for(int i = 0; i < 3; i++) t[i] = new int[5]; 
+4
source share
3 answers

You have * in the wrong place. Try:

 int **t = new int *[3]; 
+7
source

Does vector< vector< int > > ?

+2
source

You can โ€œsmoothโ€ a 2D matrix into a 1D array by storing its elements in a convenient container such as std::vector (this is more efficient than having vector<vector<T>> ). Then you can match the index of the 2D matrix (row, column) with the index of the 1D array.

If you store elements in a matrix differently, you can use the following formula:

 1D array index = column + row * columns count 

You can wrap this in a convenient C ++ class ( operator() overload for proper access to the matrix element):

 template <typename T> class Matrix { public: Matrix(size_t rows, size_t columns) : m_data(rows * columns), m_rows(rows), m_columns(columns) {} size_t Rows() const { return m_rows; } size_t Columns() const { return m_columns; } const T & operator()(size_t row, size_t column) const { return m_data[VectorIndex(row, column)]; } T & operator()(size_t row, size_t column) { return m_data[VectorIndex(row, column)]; } private: vector<T> m_data; size_t m_rows; size_t m_columns; size_t VectorIndex(size_t row, size_t column) const { if (row >= m_rows) throw out_of_range("Matrix<T> - Row index out of bound."); if (column >= m_columns) throw out_of_range("Matrix<T> - Column index out of bound."); return column + row*m_columns; } }; 
0
source

All Articles