C++ Vectors and Dynamic Arrays
Dynamic Arrays
Dynamic memory allocation in C/C++ refers to performing memory allocation manually by programmer.
One use of dynamically allocated memory is to allocate memory of variable size which is not possible with compiler allocated memory.
The most important use is flexibility provided to programmers. We are free to allocate and deallocate memory whenever we need and whenever we don’t need anymore. There are many cases where this flexibility helps.
For normal variables like `int a`, `char str[10]', etc, memory is automatically allocated and deallocated. For dynamically allocated memory like int *A = new int[10], it is the programmer's responsibility to deallocate memory when no longer needed. If the programmer doesn’t deallocate memory, it causes a memory leak.
C offers malloc() and calloc() functions to allocate memory dynamically at run time and uses free() function to free dynamically allocated memory. C++ supports these functions while also offering two operators new and delete that perform the task of allocating and freeing the memory in a better and easier way.
C++ code to demonstrate the use of new and delete
Vectors
Vectors are the same as dynamic arrays with the ability to change themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end.
Certain functions associated with the vector are
- begin()– Returns an iterator pointing to the first element in the vector
- end()– Returns an iterator pointing to the theoretical element that follows the last element in the vector
- rbegin()– Returns a reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to the first element
- rend() – Returns a reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end)
- cbegin() – Returns a constant iterator pointing to the first element in the vector.
- cend() – Returns a constant iterator pointing to the theoretical element that follows the last element in the vector.
- crbegin()– Returns a constant reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to the first element
- crend()– Returns a constant reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end)
C++ program to demonstrate vectors in C++