vector::shrink_to_fit function


This function provides a way to decrease the capacity of the vector to the size of the vector.This function is added in C++11.

void shrink_to_fit( ); ( C++11 )

Parameters:
none

Return type
none

The call of this function is nonbinding.By nonbinding we mean the compiler can actually call this function and reduce the capacity to fit the size or it may ignore this function call.The compiler can ignore this call if optimization of the program is required.

Link:vector::push_back function

Code example

vector<int> vec ;

vec.reserve( 4 ) ;

vec.push_back(12) ;
vec.push_back(90 ) ;
vec.push_back( 90 ) ;

vec.shrink_to_fit() ;

cout<< vec.capacity( ) << endl
<< vec.size( ) << endl ;

cout<< “(vec.capacity( )== vec.size()) =” << (vec.capacity( ) == vec.size() ) << endl ;

Output

3
3
(vec.capacity( )== vec.size()) = 1

Here the function is called so the capacity is reduced to 3 which is the size of the vector.





Link:vector::capacity function

The function call might invalidate iterators ,pointers and reference pointing to the vector.Since the iterators ,pointers and reference are invalidated accessing them will give some undefined values.

Code example

vector<string> vecSt;

vecSt.reserve( 3 ) ;

vector<string> ::iterator vecStIt=vecSt.begin( ) ;

vecSt.push_back(“Happy”) ;
vecSt.push_back(” String”) ;

cout<< vecSt[0] << vecSt[1] << endl ;

vecSt.shrink_to_fit( ) ;

cout<< vecSt[0] << ” ” << vecSt[1] << endl ; ///undefined values

Output

Happy String
undefined undefined


Conclusion

Another nonbinding function call besides shrink_to_fit() is the reserve() function call when the argument passed is less than the size of the vector.Since,a capacity of a vector can never be lesser than the size of the vector the call to reserve() memory lesser than the size is neglected by the compiler.

Link :vector::reserve function


 


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