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; } };
source share