• Register
1,240 points
10 7 4

Vectors are very similar to the dynamic arrays but they have the ability to resize itself automatically whenever an element is inserted or deleted. Their storage is being handled by the container automatically.

In this article we will check if a vector is empty or not.

 

Approach

For checking if the vector container is empty or not, we have to use the function empty(). If the vector is empty then it will return TRUE otherwise FALSE.

vectorname.empty()
Parameters :
No parameters are passed.
Returns :
True, if vector is empty
False, Otherwise

Example

Input  : myvector = 1, 2, 3, 4, 5
         myvector.empty();
Output : False

Input  : myvector = {}
         myvector.empty();
Output : True

Exceptions

The only exception is that whenever a parameter is passed it shows an error like this.

// CPP program to illustrate 
// Implementation of empty() function 
#include <iostream> 
#include <vector> 
using namespace std; 
  
int main() 
{ 
    vector<int> myvector{}; 
    if (myvector.empty()) { 
        cout << "True"; 
    } 
    else { 
        cout << "False"; 
    } 
    return 0; 
} 

Output

True

Applications

There can be so many applications of checking if the vector container is empty or not. For example see this program.

There is a list given of integers, and we have to find the sum of all the integers.

In this example we will proceed like this.

1. Check if the vector is empty, if not add the back element to a variable initialised as 0, and pop the back element.

2. Repeat this step until the vector is empty.

3. Print the final value of the variable.