In this C++ tutorial, you will learn about vector::resize() function, its syntax, and how to use this function to modify the size of a vector, with example programs.

C++ Vector resize() function

resize() function modifies this vector to a specified new size.

If the new size is greater than the size of the given vector, new elements are added to this vector.

If the new size is less than the size of the given vector, trailing elements are deleted from this vector to match the vector’s size to this new size.

Syntax

The syntax of resize() function with new size is

void resize(size_type new_size);

The syntax of resize() function with new size and default value for new elements is

void resize(size_type new_size, Type value);
ADVERTISEMENT

Examples

1. New size for vector is greater than original size

In the following C++ program, we define a vector with three elements, and resize this vector to 5.

main.cpp

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<string> names{ "apple", "banana", "cherry" };
    names.resize(5);
    for ( int i = 0; i < names.size(); i++ ) {
        cout << i << " - " << names.at(i) << endl;
    }
}

Output

0 - apple
1 - banana
2 - cherry
3 - 
4 - 
Program ended with exit code: 0

2. New size for vector is less than original size

In the following C++ program, we define a vector with three elements, and resize this vector to 1.

main.cpp

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<string> names{ "apple", "banana", "cherry" };
    names.resize(1);
    for ( int i = 0; i < names.size(); i++ ) {
        cout << i << " - " << names.at(i) << endl;
    }
}

Output

0 - apple
Program ended with exit code: 0

3. Resize vector with default value

In the following C++ program, we define a vector with three elements, resize this vector to 5, and also provide default value to resize() function.

main.cpp

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<string> names{ "apple", "banana", "cherry" };
    names.resize(5, "none");
    for ( int i = 0; i < names.size(); i++ ) {
        cout << i << " - " << names.at(i) << endl;
    }
}

Output

0 - apple
1 - banana
2 - cherry
3 - none
4 - none
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned the syntax of Vector resize() function, how to use this function to resize a vector to specific size, with examples.