如何在C++中动态创建新的 2D 数组

How create dynamically new 2D array in C++

本文关键字:2D 数组 创建 动态 C++      更新时间:2023-10-16

如主题如何在C++中创建新的 2D 数组?下面的代码不能很好地工作。

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 矩阵"展平"为一维数组,将其元素存储在像 std::vector 这样的方便容器中(这比拥有 vector<vector<T>> 更有效)。然后,您可以将 2D (row, column)矩阵索引映射到 1D 数组索引。

如果按行将元素存储在矩阵中,则可以使用如下公式:

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