how to free the vector c++

#include <iostream>
#include <vector>

int main() {
    std::vector<int> myVector = {1, 2, 3, 4, 5};

    // Clearing the vector
    myVector.clear();

    // Shrinking the vector
    std::vector<int>().swap(myVector);

    return 0;
}

Explanation:

  1. #include <iostream>: Includes the input-output stream header file.
  2. #include <vector>: Includes the vector header file.
  3. int main() { ... }: Entry point of the program.
  4. std::vector<int> myVector = {1, 2, 3, 4, 5};: Declares a vector named myVector and initializes it with values {1, 2, 3, 4, 5}.
  5. myVector.clear();: Clears the contents of the vector, making it empty.
  6. std::vector<int>().swap(myVector);: Creates a temporary empty vector and swaps its contents with myVector. This effectively deallocates the memory previously held by myVector and makes it empty.

This code demonstrates two different ways to free the memory associated with a vector in C++. The first method uses the clear() function to remove all elements from the vector, leaving it empty. The second method uses the swap() function with a temporary empty vector to release the memory occupied by the vector myVector.