In C ++ programming language, array operations are a very basic and important application technology. In this article, we will introduce the operations related to C ++ two-dimensional array initialization, so that you can master the application technology in this area. The two-dimensional array of C ++ cannot be initialized using variables. The following code is certainly not compiled:
- int i=5;
- int j=4;
- int a[i][j];
Code like this must be the experience of many C ++ beginners like me. If the array is determined in the compilation phase, the variable cannot be used as the dimension of the array. below, we use a template class to complete the C ++ two-dimensional array initialization function.
- Template <class T>
- Class Array2D {
- Private:
- T * pData;
- Int dim1;
- Int dim2;
- Int dim1Index;
- Class Array1D {
- Private:
- Int length;
- T * start;
- Public:
- Array1D (T * start, int length): length (length), start (start ){}
- T & operator [] (int index ){
- If (index> length ){
- Throw out_of_range ("the second dimension of the array is out of bounds ");
- } Else {
- Return * (start + index );
- }
- }
- };
- Public:
- Array2D (int dim1, int dim2 ){
- This-> dim1dim1 = dim1;
- This-> dim2dim2 = dim2;
- Int size = dim1 * dim2;
- PData = new T [size];
- }
- Array1D operator [] (int index ){
- Return Array1D (pData + index * dim1, dim2 );
- }
- Void print (){
- For (int I = 0; I <dim1; I ++ ){
- For (int j = 0; j <dim2; j ++ ){
- Cout <* (pData + dim1 * I + j) <"";
- }
- Cout <endl;
- }
- }
- };
- Int main (){
- Int index1 = 2;
- Int index2 = 2;
- Array2D <int> test (index1, index2 );
- Test [0] [0] = 1;
- Test [0] [1] = 2;
- Test [1] [0] = 3;
- Test [1] [1] = 4;
- Test. print ();
- }
Using a template class to implement this function is a good choice in C ++ two-dimensional array initialization. However, in practice, it is rarely written in this way, this is the method provided in more than tive C ++ to demonstrate the proxy mode. Array1D exists as a proxy class.