Resize Dynamic Arrays in C++: 2 Easy Methods

In C++, dynamic arrays can be resized using the following two methods:

  1. Using the new and delete operators:
  2. Create a new larger array.
  3. Copy the elements from the original array to a new array.
  4. Release the memory of the original array.
  5. Point the pointer to the new array.
  6. Sample code:
  7. 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.
  8. Use the standard library container std::vector.
  9. std::vector is a dynamic array container provided by the C++ standard library, which can automatically resize itself.
  10. 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.
  11. Example code:
  12. #include
    // …
    std::vector vec; // 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.

bannerAds