How to check whether a vector is empty or not in C++

In this post, I will try to explain every possible way in which you can check whether a vector in C++ is empty or not. So there are two primary methods to check the emptiness of a vector. The first one is the .size() method while the second one is the .empty() method.
Here is a detailed explanation of the two methods mentioned above:

The ‘.size()’ method

The ‘.size()‘ method returns an unsigned long integer equal to the size of the vector. The general syntax of the ‘.size()‘ function is :

#include<bits/stdc++.h>
using namespace std;

int main(){
    vector < int > v;
    cout<<"The size of this newly created vector is "<<v.size()<<endl;
}

(Here the first line of the code is to enable us to use the various functionalities of the Standard Template Library of C++, whereas the second line is to avoid using std:: in front of every function, like ‘<<cout’  in place of  ‘<<std::cout’) The output of the following code is :

The size of this newly created vector is 0

Now if we insert an element into the vector

v.push_back(1);
cout<<"New size of this vector is "<<v.size()<<endl;

The output of the above code is :

New size of this vector is 1

Hence we have found a way to check whether a vector is empty or not! If the size of the vector is 0, then the vector has no elements i.e. the vector is empty, else it is not.

The ‘.empty()’ method

The ‘.empty()‘ method is yet another way to know whether a vector is empty or not. The ‘.empty()‘ method returns True if the vector is empty, otherwise it returns False.
The syntax for using the function is :

#include<bits/stdc++.h> 
using namespace std;
int main(){ 
    vector < int > v; 
    if(v.empty() == true){
        cout<<"The vector is empty."<<endl;
    }
    else{
        cout<<"The vector is not empty."<<endl;
    }
}

Here as you can see, the vector v is empty, hence the ‘if’ statement evaluates to true and the output will be :

The vector is empty.

Now, if we insert an element into the vector :

#include<bits/stdc++.h> 
using namespace std; 
int main(){ 
    vector < int > v; 
//inserting an element into the vector 
    v.push_back(10);
    if(v.empty() == true){ 
        cout<<"The vector is empty."<<endl; 
    }
    else{ 
        cout<<"The vector is not empty."<<endl; 
    } 
}

The new output will be :

The vector is not empty.

So these were the major methods to check whether a vector in C++ is empty or not. Please drop a comment below if you have any queries regarding this topic.
Related topics:
Count the number of unique elements in a vector
Vector Insert function

Leave a Reply

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