考虑两种类型的数组声明:
T x [rows * cols]; // type 1
T y [rows][cols]; // type 2
我通常使用第一种类型(类型 1)然后我知道使用 x[row * cols + col] 进行索引
但是,如果我想将二维数组复制到模拟二维数组的一维数组中,即:复制 type2 -> type1。如果保证这些在内存中以相同的方式布局,我可以只对另一个进行 memcpy 吗?目前我有一个这样的循环,但如果两者的内存布局相同,我想我可以做一个 memcpy。考虑下面的公共(public)构造函数。
public:
// construct a matrix from a 2d array
template <unsigned int N, unsigned int M>
Matrix ( T (&twoDArray)[N][M] ) : rows_(N), cols_(M), matrixData_(new T[rows_*cols_])
{
// is there a refactor here? Maybe to memcpy?
for ( unsigned int i = 0; i < rows_ ; ++i )
{
for ( unsigned int j = 0; j < cols_ ; ++j )
{
matrixData_[ i * cols_ + j ] = twoDArray[i][j];
}
}
}
private:
unsigned int rows_;
unsigned int cols_;
T* matrixData_;
最佳答案
这取决于,但通常编译器会使简单的 T x[rows][columns] 表现得像 T x[rows * columns。除非你像这样动态声明内存
T** x = new T*[rows];
for (int i = 0; i < rows; ++i)
x[i] = new T[columns];
在这个例子中它们是不同的。
关于c++ - 在内存中设置的二维数组是否与模拟二维数组的一维数组连续相似?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18414196/