vector::resize function


The vector resize function will resize the vector to contain the specified number of elements.There are two types of resize function.

T : type of the data.

void resize(size_t new_size);
void resize(size_t new_size , const T& x);

More about the two functions is provided below.



void resize(size_t new_size);


Parameters:
new_size – The new size of the vector.

Return type
void

Points to note:

i)If the new size is smaller than the previous size the vector is truncated and the data is lost. The capacity however remains unchanged.

ii)If the new size is bigger than the previous size, the incremented storage is initialized with the default value.This means for int,float and char type the incremented vector is assigned 0 ,if the type is string an empty string ( “” ) is assigned.

The capacity of the vector may be bigger than the new vector size.

Link :vector capacity()
Code example :When the vector size is shrunken.

vector<int> vec={ 23 , 45 , 78 , 89 }

cout<< “Capacity before shrinking=” << vec.capacity( ) ;

vec.resize( 2 ) ;

for( auto elem:vec )
{
cout<< elem << ” ” ;
}

cout<< “\nCapacity=” << vec.capacity( ) ;

Output,

Capacity before shrinking = 4
23 45
Capacity=4 ;

Code example :When the vector size is enlarge.

vec.resize( 7 ) ;

for( auto elem:vec )
{
cout<< elem << ” ” ;
}

cout<< “\nCapacity=” << vec.capacity( ) ;

Output,

23 45 0 0 0 0 0
Capacity= 8

The capacity is larger then the enlarge size.






void resize(size_t new_size , const T& x);


Parameters:
new_size – The new size of the vector.

x – The value assigned to the incremented size.

Return type
void

Points to note:

i)If the new size is smaller than the previous size the vector is truncated and the data is lost. The capacity however remains unchanged.

ii)If the new size is bigger than the previous size,the incremented storage is initialized with the value provided as the second argument.

The capacity of the vector may be bigger than the new vector size.

vector<string> vec={ “New ” , “shoes ” , “and” , ” string” , “ling” } ;

cout<< “Capacity before shrinking=” << vec.capacity( ) ;

vec.resize( 3 , 5 ) ;

for( auto elem:vec )
{
cout<< elem << ” ” ;
}

cout<< “\nCapacity=” << vec.capacity( ) ;

Output

Capacity before shrinking=5
New shoes and
Capacity=5

Code example :When the vector size is enlarge.

vec.resize( 5 , ” Code” ) ;

for( auto elem:vec )
{
cout<< elem << ” ” ;
}

cout<< “\nCapacity=” << vec.capacity( ) ;

Output,

New shoes and Code Code
6


 


Stop wasting time,earn money($$$) from your website-Join Now!