c++ - Is a 2d array set up in memory contiguously similar to a 1d array simulating a 2d one? -
consider 2 type of array declarations:
t x [rows * cols]; // type 1 t y [rows][cols]; // type 2
i use first type ( type 1) know index using x[row * cols + col]
however if want copy 2d array 1d array simulating 2d array ie: copy type2 -> type1. if these guaranteed laid out same way in memory can memcpy of 1 other? have loop such if memory same layout in both thinking can memcpy. consider following public constructor below.
public: // construct matrix 2d array template <unsigned int n, unsigned int m> matrix ( t (&twodarray)[n][m] ) : rows_(n), cols_(m), matrixdata_(new t[rows_*cols_]) { // there refactor here? maybe memcpy? ( unsigned int = 0; < rows_ ; ++i ) { ( unsigned int j = 0; j < cols_ ; ++j ) { matrixdata_[ * cols_ + j ] = twodarray[i][j]; } } } private: unsigned int rows_; unsigned int cols_; t* matrixdata_;
a 2d array (the kind declared) guaranteed contiguous in memory. doesn't mean should use memcpy on it. not in template doing, because memcpy may not work correctly t
. can keep have. here how might write though (if can't use c++11, use regular counting loop):
template <unsigned int n, unsigned int m> matrix ( t (&twodarray)[n][m] ) : rows_(n), cols_(m), matrixdata_(new t[rows_*cols_]) { t * out = matrixdata_; (auto const & sub : twodarray) out = std::copy(std::begin(sub), std::end(sub), out); }
or better yet, use std::vector
. don't have implement copy constructor, assignment operator, or destructor. (you have implemented 3 of those, right?)
Comments
Post a Comment