how to clear vector c++

To clear a vector in C++, you can use the clear() function provided by the vector class. This function removes all the elements from the vector, effectively making it empty. Here are the steps to clear a vector in C++:

  1. Include the necessary header file: To use vectors in C++, you need to include the <vector> header file at the beginning of your code.

  2. Create a vector: Declare and initialize a vector with some elements.

  3. Call the clear() function: Use the clear() function on the vector object to remove all the elements from the vector.

Here's an example code snippet that demonstrates how to clear a vector in C++:

#include <iostream>
#include <vector>

int main() {
    // Create a vector
    std::vector<int> numbers = {1, 2, 3, 4, 5};

    // Clear the vector
    numbers.clear();

    // Print the vector
    for (int number : numbers) {
        std::cout << number << " ";
    }

    return 0;
}

In this example, we include the necessary header file <vector>, create a vector called numbers with some initial values, and then call the clear() function to remove all the elements from the vector. Finally, we print the vector, which will output nothing since it is empty.

By calling the clear() function on a vector, you ensure that it is empty and ready to be used again for storing new elements.