English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ vector resize() Usage and Example

C++ Vector (Container)

It will change the size of the vector to the specified size value

Change the size to4, the new value is

Syntax

The syntax of vector v is:

v.resize(n, val);

Parameters

n: This is the new size of the vector.

val: If n is greater than the size of the current vector, insert the value (val) into the space added.

Return value

It does not return any value.

Example1

Let's look at a simple example where n is less than the size of the current vector.

#include<iostream>
#include<vector>
using namespace std;
int main()
{
	vector<int> v;
	for(int i=1;i<=10;i++)
	{
	v.push_back(i);
	}
	cout << "The initial elements are ":;
	++)
	cout << v[i] << " \";",
	v.resize(5);
	
	cout << "Adjust its size to",5After that, the elements are ";
	++)
	cout << v[i] << " \";",
	return 0;
}

Output Result:

The initial elements are: 1 2 3 4 5 6 7 8 9 10 
Adjust its size to5After that, the elements are: 1 2 3 4 5

Example2

Let's look at a simple example where n is greater than the size of the current vector.

#include<iostream>
#include<vector>
using namespace std;
int main()
{
	vector<string> v1{"java","C","C++");
	cout << "v1The elements are :
	for(int i = 0; i < v1.size();i++)
	cout << v1[i] << "  ";
	v1.resize(5,".Net");
	for(int i = 0; i < v1.size();i++)
	cout << v1[i] << "  ";
	return 0;
}

Output Result:

v1The elements are :java C C++ java C C++ .Net .Net

C++ Vector (Container)