Last Updated : 11 Jul, 2025
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:
C++
#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;
}
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.
C++
Parameters:
Return Value:
The below examples demonstrate the use of vector resize() function in different cases:
Decrease the Size of VectorResizing the vector to a smaller size than its current one will truncate elements from the end.
C++
#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;
}
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 C++
#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;
}
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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4