Resize Dynamic Arrays in C++: 2 Easy Methods
In C++, dynamic arrays can be resized using the following two methods:
- Using the new and delete operators:
- Create a new larger array.
- Copy the elements from the original array to a new array.
- Release the memory of the original array.
- Point the pointer to the new array.
- Sample code:
- Create an array with an initial size of 10.
// …
Create a new larger array with a size of 20.
for (int i = 0; i < 10; i++) { Copy elements from the original array to the new array. } Release the memory of the original array. Point the pointer to the new array. - Use the standard library container std::vector.
- std::vector is a dynamic array container provided by the C++ standard library, which can automatically resize itself.
- Adding elements to a container using the push_back method of std::vector will automatically expand the container’s capacity when it is not enough.
- Example code:
- #include
// …
std::vectorvec; // Create an empty vector
// …
vec.push_back(10); // Add an element to the vector, it will automatically increase in size if the capacity is exceeded
Both methods mentioned above can achieve dynamic array resizing, but using std::vector is more concise and convenient, so it is recommended to use it for handling dynamic arrays.