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