c++ vector resize
The resize()
function in C++ vector is used to change the size of the vector, either by increasing or decreasing its capacity. When calling resize()
, you need to specify the new size of the vector. If the new size is larger than the current size, the additional elements are initialized with a default value or the one provided. If the new size is smaller than the current size, the extra elements are removed from the vector.
Here's a simple example to demonstrate the usage of resize()
:
#include <iostream>
#include <vector>
int main() {
std::vector<int> myVector;
// Resizing the vector to contain 5 elements, each initialized with value 10
myVector.resize(5, 10);
// Now the vector contains: [10, 10, 10, 10, 10]
// Resizing the vector to contain only 3 elements
myVector.resize(3);
// Now the vector contains: [10, 10, 10]
return 0;
}