Implement variable-length array dynamic array allocation in C ++

Source: Internet
Author: User
 
 

Implement variable-length array in C ++

1. variable-length one-dimensional array

The variable-length array is an array that cannot determine the length of the array during compilation and the program needs to dynamically allocate memory space during runtime. The simplest way to implement a variable-length array is a variable-length one-dimensional array. You can do this:

// File name: array01.cpp
# Include <iostream>
Using namespace STD;

Int main ()
{
Int Len;
Cin> Len;
// Use the pointer P to point to the new dynamically allocated memory space with the length Len * sizeof (INT)
Int * P = new int [Len];
...........
Delete [] P;
Return 0;
}

Note int * P = new int [Len]; you cannot do this:
Int P [Len];
The C ++ compiler reports an error saying that the Len size cannot be determined because the array is declared in this form and the array size needs to be determined during compilation. And this does not work either:
Int P [] = new int [Len];
The compiler will say that the int * type cannot be converted to the int [] type, because the first address of the memory will be returned after a memory space is opened up with new, so we need to assign this address to a pointer, so we need to use int * P = new int [Len];

Array01.cpp implements a variable-length one-dimensional array, but to develop a good habit, you should be sure to deregister the pointer P so that the program can release the memory space opened with new.
Of course, using the vector in the C ++ standard template library (STL) can also implement a variable-length array:

// File name: array02.cpp
# Include <iostream>
# Include <vector>
Using namespace STD;

Int main ()
{
Int Len;
Cin> Len;
Vector <int> array (LEN); // declare a variable-length Array

For (INT I = 0; I <Len; I ++)
{
Array [I] = I;
Cout <array [I] <"/t ";
}
Return 0;
}

The variable length array reminds me of the arraylist in the vector and C # in Java. util packages. They can also implement variable length arrays in their respective languages. However, the vector in C ++ cannot have a hosted garbage collection mechanism like C # to recycle the occupied memory space, but you can call it after using the vector ~ The vector () destructor releases the memory.

2. variable-length n-dimensional array
It is difficult to implement a variable-length n-dimensional array. However, two-dimensional arrays are often used in engineering and software design applications. Therefore, we will introduce a variable-length two-dimensional array here, A variable-length n-dimensional array can be implemented in a similar way. First, let's look at a typical example of using C to implement a variable-length two-dimensional array:

// File name: array03.c
# Include <stdio. h>
# Include <malloc. h>
 
Void main ()

{
Int X, Y, I, j;
Float ** A, * B;
Printf ("Enter the number of rows of the linear equations you have solved X: x = ");
Scanf ("% d", & X );
Printf ("Enter the number of columns of the linear equations you have solved. Y: Y = ");
Scanf ("% d", & Y );
 
A = (float **) malloc (sizeof (float *) * X );
B = (float *) malloc (sizeof (float) * X );
For (I = 0; I <X; I ++)
{
* (A + I) = (float *) malloc (sizeof (float) * y );
}
 
/* Read data */
 
Printf ("Enter the coefficient value in the order of rows (% d in total):", x * y );
For (I = 0; I <= X-1; I ++)
For (j = 0; j <= Y-1; j ++)
Scanf ("% F", & A [I] [J]);
Printf ("Enter the constant values in the order of columns (% d in total):", X );
For (j = 0; j <= X-1; j ++)
Scanf ("% F", & B [J]);
 
Printf ("the Augmented Matrix of the input equations is:/N ");
For (I = 0; I <= X-1; I ++)
{
For (j = 0; j <= Y-1; j ++)
Printf ("%. 5f", a [I] [J]);
Printf ("%. 5f", B [I]);
Printf ("/N ");
}
Free (B );
For (I = 0; I <X; I ++)
Free (* (a + I ));
 
}

How can we implement it with C ++? In C ++, space can be dynamically opened and released through the new and delete operators. The functions of the new function are similar to those of the malloc function in C, and the functions of the delete function are similar to those of the free function in C. Two methods can be used to implement a variable-length two-dimensional array using C ++: the double pointer method and the vector (vector) method in STL.

First, we will introduce the double pointer method. Here the double pointer refers to a pointer like a pointer. For example, you can declare an array like this:
Int ** P = new int * [num1];
Apply for a set of memory space for each * P (num1 total * P:
For (INT I = 0; I <num1; ++ I)
P [I] = new int [num2];
Num1 indicates the number of rows, and num2 indicates the number of columns in the array. The test source code is as follows:

// File name: array04.cpp
# Include <iostream>
# Include <iomanip>
Using namespace STD;

Int main ()
{
Int num1, // number of rows
Num2; // Number of Columns

Cout <"Please enter the number for row and column:" <Endl;
Cin> num1> num2;

// Open up space for two-dimensional arrays
Int ** P = new int * [num1];
For (INT I = 0; I <num1; ++ I)
P [I] = new int [num2];

For (Int J = 0; j <num1; j ++)
{
For (int K = 0; k <num2; k ++)
{
P [J] [k] = (J + 1) * (k + 1 );
Cout <SETW (6) <p [J] [k] <':' <SETW (8) <& P [J] [k];
}
Cout <Endl;
}

// Release the space occupied by the two-dimensional array
For (INT m = 0; m <num1; m ++)
Delete [] P [m];
Delete [] P;

Return 0;
}

The running result is as follows:

Please enter the number for row and column:
4 5
1: 004915f0 2: 004915f4 3: 004915f8 4: 004915fc 5: 00491600
2: 00491180 4: 00491184 6: 00491188 8: 0049118c 10: 00491190
3: 00491140 6: 00491144 9: 00491148 12: 0049114c 15: 00491150
4: 00491100 8: 00491104 12: 00491108 16: 0049110c 20: 00491110
Press any key to continue

In the program list, array04.cpp shows the address of the allocated memory space unit. As you can see, the address space between array rows is not consecutive because the array space is dynamically allocated, because the address space of array elements in different rows is allocated with different new. The address space between columns in each row is continuous.

How can we use vector to implement a two-dimensional array? The following provides the source code:

// File name: array05.cpp
# Include <iostream>
# Include <vector>
# Include <iomanip>
Using namespace STD;
Int main ()
{
Int I,
J,
M, // number of rows
N; // Number of Columns

Cout <"input value for M, N :";
Cin> m> N;
 
// Note the following line: there must be a space between the vector <int ">! Otherwise it will be considered as a heavy load "> ".
Vector <vector <int> vecint (M, vector <int> (n ));
For (I = 0; I <m; I ++)
For (j = 0; j <n; j ++)
Vecint [I] [J] = I * J;

For (I = 0; I <m; I ++)
{
For (j = 0; j <n; j ++)
Cout <SETW (5) <vecint [I] [J] <":" <SETW (9) <& vecint [I] [J];
Cout <Endl;
}

Return 0;
}

The running result is as follows:

Input value for M, N: 3 4
0: 00491180 0: 00491184 0: 00491188 0: 0049118c
0: 00491140 1: 00491144 2: 00491148 3: 0049114c
0: 00491100 2: 00491104 4: 00491108 6: 0049110c
Press any key to continue

As you can see, The Address Allocation of elements in the vector also has the same characteristics as the two-dimensional array implemented by the double pointer. However, the method of using vector is much simpler than using double pointers. it is safer to allocate memory space and the array initialization code is simpler, therefore, we recommend that you use the vector in STL to implement a variable-length multi-dimensional array. The following is a variable-length 3D array :)

// File name: array06.cpp
# Include <iostream>
# Include <vector>
# Include <iomanip>
Using namespace STD;
Int main ()
{
Int I,
J,
K,
M, // One-dimensional coordinate
N, // two-dimensional coordinate
L; // 3D coordinates

Cout <"input value for m, n, l :";
Cin> m> N> L;
Vector <vector <int> vecint (M, vector <int> (n, vector <int> (L )));
For (I = 0; I <m; I ++)
For (j = 0; j <n; j ++)
For (k = 0; k <L; k ++)
Vecint [I] [J] [k] = I + J + K;

For (I = 0; I <m; I ++)
{
For (j = 0; j <n; j ++)
{
For (k = 0; k <L; k ++)
Cout <SETW (5) <vecint [I] [J] [k] <":" <SETW (9) <& vecint [I] [J] [k];
Cout <Endl;
}
Cout <Endl;
}

Return 0;
}

Running result:
Input value for m, n, l: 2 3 4
0: 000000fe0 1: 000000fe4 2: 000000fe8 3: 000000fec
1: 000000fa0 2: 000000fa4 3: 000000fa8 4: 000000fac
2: 000000f60 3: 000000f64 4: 000000f68 5: 000000f6c

1: 00366ec0 2: 00%ec4 3: 00%ec8 4: 00%ecc
2: 000000e80 3: 000000e84 4: 000000e88 5: 000000e8c
3: 000000e40 4: 000000e44 5: 000000e48 6: 000000e4c

Press any key to continue

Using a similar method, you can also use a vector to implement a four-dimensional, five-dimensional, or even an n-dimensional variable-length array. However, directly using a pointer to implement an n-dimensional array will make your head larger :)

(All programs in this article are compiled and run in vc6)
<Post>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.