如主题如何在 C++ 中创建新的二维数组?下面的代码不能很好地工作。
int** t = new *int[3];
for(int i = 0; i < 3; i++)
       t[i] = new int[5];
如主题如何在 C++ 中创建新的二维数组?下面的代码不能很好地工作。
int** t = new *int[3];
for(int i = 0; i < 3; i++)
       t[i] = new int[5];
你有一个*错误的地方。尝试:
int **t = new int *[3];
会vector< vector< int > >工作吗?
您可能希望将 2D 矩阵“展平”为 1D 数组,将其元素存储在一个方便的容器中std::vector(这比使用 更有效vector<vector<T>>)。然后您可以将二维(row, column)矩阵索引映射到一维数组索引。
如果将元素按行存储在矩阵中,则可以使用如下公式:
1D array index = column + row * columns count
您可以将其包装在一个方便的 C++ 类中(operator()为正确访问矩阵元素而重载):
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;
    }
};