C++ vector::shrink_to_fit function

The C++ vector shrink_to_fit function provides a way to decrease the capacity of the vector to the size of the vector(the number of values in 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 reserve

 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


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.

Link: Vector push_back

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,when it is call with the argument less than the size of the vector.

Since the capacity of a vector can never be lesser than the size of the vector,when reserve() is called and the memory size to be reserve is lesser than the size then the call is neglected by the compiler.




Leave a Reply

Your email address will not be published. Required fields are marked *