vector::empty function


The vector empty() function returns true(1) if the vector is empty,if it is not empty it returns false(0).

bool empty( ) const;

A vector is considered as empty if the size is 0.The capacity may or may not be 0.But obviously if the capacity is 0 the size is also 0.So for the vector to be empty the begin() and end() are equal.

Parameters:
none

Return type
bool – Returns true or false.

Code example:

vector<int> vec={ 2 , 3 };

cout<< vec.empty( ) << endl ;

vec.clear( ) ;

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

Output

0 (false)
Capacity=2
1 (true)

The capacity is not 0 but the vector is considered as empty because the size is 0.

Link:read more about clear()

Here is another code example,which shows that empty() returns true when begin() and end() are equal.

vector<string> vecSt ;

cout<< (vecSt.begin( ) == vec.end( )) << endl
<< vecSt.empty( ) << endl << endl ;

vecSt.reserve( 2 );
vecSt.push_back(“String”);

cout<< ( vecSt.begin( ) == vec.end() ) << endl
<< vecSt.empty( ) ;

Output,

1(true)
1(true)

0(false)
0(false)

After calling reserve() and push_back() the size becomes 1.Hence we get false as the returned value for empty().

Link:Read more about reserve()