To begin with, let's define what a dynamic array is. Since the time of C, arrays exist, but their feature was a fixed size, which was indicated at creation and did not change anymore. Thanks to this, they are called static arrays. Obviously, a dynamic array means that it can change its size while the program is running. And it can also be created when the number of proposed elements is even approximately unknown, that is, empty.
Dynamic memory management
There is such a thing as dynamic memory management. This approach to programming allows you to maximize the use of computer memory. In C ++, this process is controlled by the new and delete operations. The new operation reserves memory in the area of dynamic memory or also called heap (free store or heap in English). Accordingly, the delete operation releases the reservation.
According to programming standards, dynamic memory needs to be monitored and cleaned in a timely manner, so the new and delete operations are often used in pairs. This principle has long been outdated. Its roots have been growing since the time when operating systems poorly monitored memory or simply did not know how to clean it on their own. Now the OS always clears the memory after the program runs. However, explicit memory cleansing is a sign of good form in programming.
The new operation reserves memory for an object of a certain type and returns an address to this memory. If memory allocation for any reason cannot be done, then the operation will return a null pointer (a pointer that does not refer to anything) and throw an exception. The new operator works with objects of any data type: double, char, int, etc. The allocation of memory and its removal are as follows.
int *p = new int;
One-dimensional array
Creating a one-dimensional dynamic array is the same as creating a variable on the heap.
double *a = new double[10];
After the delete operator, it is necessary to indicate square brackets to indicate for the program the upcoming operation as the release of not only the pointer to the array, but also the array itself.
Two-dimensional array
Creating a one-dimensional dynamic array is a trivial task. And if we need a multidimensional array ...
double **ma = new double *[5];
Thus, a dynamic array is created in C ++ with a dimension of 5 by 10. Literally, this means at the first step the allocation of an array of 5 elements in memory. And then, in the second step, allocating memory for an array of 10 elements and writing the address to it in the previous array, and so on for each column.
Why is a second order pointer used? This is a pointer to a pointer. This is a little difficult to understand. Although the code literally tells us to get to some value stored in the array, we need to go to the address, get another address there and then we will go to the value.
Remember that the memory release construct for the array needed to be remembered? A two-dimensional array is destroyed as follows.
for(int I = 0; i < 5l i++) delete [] ma[i];
Now you can safely create even a five-dimensional array.
Where is the “dynamics"?
At the beginning, it was said that the size of the dynamic array changes during the course of the program, but in the examples above this was not explicitly indicated anywhere. Changes in the dimension of the array are made according to the following algorithm:
- A new array of the required sizes is created in memory.
- The data from the old array is overwritten into the new array.
- The old array is destroyed.
STL vector - new dynamic array
To use vectors, you need to connect <vector>.
As you know, the standard template library (STL) is equipped with a set of containers that manage collections of elements. Among the containers there are consecutive containers. They differ mainly in the ordering of elements by insertion time. In other words, the first element will always be the first, the second always the second, etc. There are other types of containers - associative, ordered by the value of the elements, and completely disordered.
One such sequential container is a vector. It manages the elements of a C ++ array in dynamic memory. These items are accessed directly by index. Due to the fact that the vector is a serial container, the addition and removal of elements occurs at the end of the array, and these operations are performed very quickly. However, the insertion of a new element in the middle or beginning of the vector is much slower, since for the implementation of this procedure you will have to move all previous elements to the current insertion number. Consider an example.
#include <vector> #include <iostream> int main() { std::vector<int> v;
As you can see from the code, working with vectors is carried out in exactly the same way as with arrays. The vectors are provided with useful additional properties, such as C ++ functions for dynamic arrays .size () and .push_back (). Strictly speaking, these member functions belong to the container.
Access to Vector Elements
Gaining access to vector elements is a topic that should be discussed separately. The following methods apply to vector elements.
V [index] | Standard Index Access |
V.at (index) | An element is accessed by index, but an exception is thrown out of range |
V.front () | The appeal to the first element of the vector |
V.back () | Access to the last element of the vector |
Obviously, the most reliable way to access a vector element is to call the .at () function, since it throws an out_of_range exception, which can be handled in a try-catch block. The operation [] and the functions .front () and .back () in the case of exceeding the allowable range work in an unpredictable way.
Two-dimensional vector
Consider the example of creating a two-dimensional dynamic array C ++ - a simple 5 by 5 matrix.
vector< vector<int> > v(5, vector<int>(5)); v[2][3] = 10; int a = v[2][3]; v[2].push_back(5);
A two-dimensional vector is a vector of vectors. And you can work with each individual vector: add and remove elements, use member functions, as shown in the example above in the last line. You can also use iterators. At first glance, the design seems intimidating. But only at first. Vectors have much greater capabilities than described in this article. They can be found in detail in the documentation.
Conclusion
In the recent past, programmers were forced to create dynamic arrays on their own, including all the necessary functions and algorithms for working with them. But with the advent of STL, they can use ready-made, well-thought-out and efficient classes. Therefore, you should not reinvent the wheel, but simply use vectors (or another suitable container). And only if necessary, work with old methods.