C++ vector resize() function
Example
Change the size of a vector:
vector<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars.resize(2);
for(string car : cars) {
cout << car << "\n";
}
Try it Yourself »
Definition and Usage
The resize()
function changes the number of elements that are in the vector.
If the resized vector is larger then the value of newly added elements can be specified.
Syntax
One of the following:
vector.resize(size_t size);
vector.resize(size_t size, <type> value);
The size_t
data type is a non-negative integer. <type>
refers to the type of the data that the vector contains.
Parameter Values
Parameter | Description |
---|---|
size | Required. The new size of the vector. |
value | Options. The value assigned to newly added elements if the vector increases in size. |
More Examples
Example
Resize a vector and add new elements to it:
vector<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars.resize(6, "Toyota");
for(string car : cars) {
cout << car << "\n";
}
Try it Yourself »
Related Pages
Read more about vectors in our Vector Tutorial.