One, C + + dynamic application of two-dimensional array
In C + +, it is not possible to apply the two-dimensional array directly, and after searching, we find a better method to apply the two-dimensional array dynamically.
The code is as follows (Matrix_type for a certain type, lines and columns):
matrix_type** Elem; // C + + two-dimensional matrix dynamic application space New matrix_type*[lines];elem[0New Matrix_type[lines * Columns]; for (int1; i < Lines; i++) 1] + Columns;
You can read and assign values directly:
0;
The advantage of applying this method to a two-dimensional array is that memory is contiguous and used directly.
Second, C + + copy constructors
When you use the following code, C + + copies the original object and assigns the value to the next object. However, there is a problem that C + + cannot copy dynamic member data when the object contains dynamic members.
classmatrix{ Public: intLines; intColumns; Matrix_type**Elem;//InitializeMatrix (); Matrix (intLinesintcolumns); ~Matrix ();}; Matrix::matrix (intLinesintcolumns) {Lines=lines; Columns=columns; //C + + two-dimensional matrix dynamic application spaceElem =Newmatrix_type*[Lines]; elem[0] =NewMatrix_type[lines *Columns]; for(inti =1; i < Lines; i++) Elem[i]= Elem[i-1] +Columns; memset (elem[0],0, Lines * Columns *sizeof(Matrix_type));} Matrix::~Matrix () {//C + + two-dimensional matrix destructionDelete elem[0]; Delete Elem;}
Matrix m2 == m2;
One way to solve this problem is to rewrite the copy constructor. The form is as follows:
//copy ConstructorMatrix::matrix (Constmatrix&m) { //because new is present in the constructor, the copy constructor must be rewrittenLines=M.lines; Columns=M.columns; //C + + two-dimensional matrix dynamic application spaceElem =Newmatrix_type*[Lines]; elem[0] =NewMatrix_type[lines *Columns]; for(inti =1; i < Lines; i++) Elem[i]= Elem[i-1] +Columns; memcpy (elem[0], m.elem[0], Lines * Columns *sizeof(Matrix_type));}
C + + Dynamic request two-dimensional array and copy constructors