When working with a 2D vector in C++, you may come across scenarios where you need to clear its contents. Clearing a 2D vector involves removing all the elements in the vector and resetting its size to zero.
To clear a 2D vector, you can use the clear()
function provided by the vector class. However, since we are dealing with a 2D vector, we need to clear each individual row within the vector as well.
Here’s an example code snippet that demonstrates how to clear a 2D vector in C++:
#include <iostream>
#include <vector>
int main() {
std::vector<std::vector<int>> myVector = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Clearing a 2D vector
for (auto& row : myVector) {
row.clear();
}
myVector.clear();
// Outputting the cleared vector
for (const auto& row : myVector) {
for (const auto& element : row) {
std::cout << element << " ";
}
std::cout << std::endl;
}
return 0;
}
In the above example, we create a 2D vector myVector
initialized with some values. We then use the range-based for
loop to iterate over each row in the vector and call the clear()
function to remove the elements in that row. Finally, we call clear()
on myVector
itself to remove all rows and reset the size to zero.
After clearing the 2D vector, we can verify its contents by outputting the elements in each row. In this example, the output will be empty since the vector has been cleared.
Remember to include the <vector>
and <iostream>
headers and compile the code using a C++ compiler.
By following these steps, you can easily clear a 2D vector in C++, ensuring that all the elements are removed and the vector is reset to an empty state.
#C++ #Vector