As in the subject how create new 2D array in C++? This code below does not work quite well.
int** t = new *int[3];
for(int i = 0; i < 3; i++)
t[i] = new int[5];
You have a *
in the wrong spot. Try:
int **t = new int *[3];
std::vector
instead of raw C-like arrays allocated with new[]
, unless there is a strong reason to do otherwise.
Would vector< vector< int > >
work?
You may want to "flatten" the 2D matrix into a 1D array, storing its elements in a convenient container like std::vector
(this is more efficient than having a vector<vector<T>>
). Then you can map the 2D (row, column)
matrix index into the 1D array index.
If you store the elements in the matrix row-wise, you can use a formula like this:
1D array index = column + row * columns count
You can wrap that in a convenient C++ class (overloading operator()
for proper matrix element access):
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;
}
};
std::vector
inside anotherstd::vector
?