In C++, the vector resize() is a built-in method used to change the size of vector container after it is declared. It can be used to increase or decrease the size of vector.
Let’s take a look at an example that illustrates the vector resize() method:
#include <bits/stdc++.h>
using namespace std;
int main() {
// Creating vector of size 5
vector<int> v(5);
// Vetor resized to 9
v.resize(9);
cout << v.size();
return 0;
}
Output
9
In the above example, we have first created a vector of size 5. But in the next statement, we changed the size of the vector to 9 elements using vector resize() function. This can be verified by checking the final size of the vector.
Syntax of Vector resize()
The vector resize() is the member method of std::vector defined inside <vector> header file.
v.resize(n, val);
Parameters:
- n: New size of vector. It can be both greater or smaller than the current size but can only be positive.
- val: Value by which extra elements of vector will be initialized. It is optional and by default is set to 0.
Return Value:
- This function does not return any value.
Examples of vector resize()
The below examples demonstrate the use of vector resize() function in different cases:
Decrease the Size of Vector
Resizing the vector to a smaller size than its current one will truncate elements from the end.
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 2, 3, 4, 5};
// Vector resized to 3
v.resize(3);
for (auto i: v)
cout << i << " ";
return 0;
}
Output
1 2 3
Explanation: Initially, the size of the vector is 5, as it is initialized with 5 elements. After that, we resize the vector to 3, reducing its size and removing the last two elements.
Increase Size and Initialize New Elements
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 4, 6};
// Vector resized to 7 and added
// elements initialized to 9
v.resize(7, 9);
for (auto i : v)
cout << i << " ";
return 0;
}
Output
1 4 6 9 9 9 9
Explanation: Initially the size of vector is 3, after that we resize the vector to 7 and initialized the added 4 elements with value 9.