How to create a dynamic array

How to create a dynamic array

The named set of the same elements is called an array. Similar data structure has the mass of obvious advantages and one shortcoming – during creation of an array it is necessary to announce in advance its size which cannot be changed further normal means. The solution of this problem consists in development of the dynamic arrays capable at any time to change quantity of the elements. And for this purpose it is possible to use as already created classes, and to implement own by means of standard means of a programming language.

Instruction

1. The main essence of a dynamic array consists in memory allocation under the data which are stored in it in that size in which it is necessary at the moment. It is the most convenient to implement this design in the form of a class – covers for an array. Here it is necessary to provide all functions executing selection and release of memory under an array and also the operators providing access to its elements.

2. Create an object of a class cover of a dynamic array, at the same time the designer will automatically allocate memory of the specified size. If in process of filling of an array the memory under elements is occupied completely, when adding the next data the following actions are made: – all information from an array is saved in temporary storage (auxiliary array); – earlier allocated memory is released by a special command (free, delete); – memory under an array of that size which is required for the containment of all data is allocated; – in a new array from temporary storage all "old" values are located and the new element is added.

3. The most optimal variant of work with dynamic arrays is use of already existing library classes. Some of the most widespread examples can call the class vector. It included all functions, necessary for functioning of a changeable array, and iterators. And the library module containing this class is delivered with any version of the compiler of language C ++.

4. Connect library of a dynamic array by means of the #include command. For creation of an object use the class vector. Movement on an array happens as well as usually, by means of indexes. Functions of adding and removal of new elements and also a number of supplementary methods are special here. Code sample of creation and work of a dynamic array of vector:#include vector; vector int Mass;//declaration of a dynamic array with intMas.push_back (10) elements;//adding of the first element – number 10 Mas.push_back (15);//adding of the second element – number 15Mas [1] = 30;//in the second element number 30Mas.pop_back registers ();//removal of the last array cell Here during creation of a dynamic array with the name Mass is surely specified type of its elements (int), the dimension in this case is not set.

Author: «MirrorInfo» Dream Team


Print