C++ vector::back function

The C++ vector back( ) function returns the last element of the vector.

T – type of the vector.

T& back( );
const T& back( ) const ;
First function

Parameters:
none

Return type
T& -A read and write reference to the last element.

Second function

Parameters:
none

Return type
T& -A read only reference to the last element.

The read and write reference type return by the first function allows us to change the last element of the vector.

 ector<string> vecSt={ “Get” , ” the” , ” string” };

cout<< vecSt.back( ) ;

vecSt.back( )=” new string” ; ///changing the last string

for( auto elem:vecSt )
{
cout<< vec[0] ;
}

Output

String
Get the new string



Leave a Reply

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