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 )|
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.
vector<int> vec ;
vec.reserve( 4 ) ;
vec.push_back(90 ) ;
vec.push_back( 90 ) ;
cout<< vec.capacity( ) << endl
<< vec.size( ) << endl ;
cout<< “(vec.capacity( )== vec.size()) =” << (vec.capacity( ) == vec.size() ) << endl ;
(vec.capacity( )== vec.size()) = 1
Here the function is called so the capacity is reduced to 3 which is the size of the vector.
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.
vecSt.reserve( 3 ) ;
vector<string> ::iterator vecStIt=vecSt.begin( ) ;
vecSt.push_back(” String”) ;
cout<< vecSt << vecSt << endl ;
vecSt.shrink_to_fit( ) ;
cout<< vecSt << ” ” << vecSt << endl ; ///undefined values
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!