Open In App

How to Check if a Vector is Empty in C++?

Last Updated : 18 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A vector is said to be empty when there are no elements present in vector. In this article, we will learn different ways to check whether a vector is empty or not.

The most efficient way to check if the vector is empty or not is by using the vector empty() function. Let’s take a look at a simple example:

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

int main() {
    vector<int> v;

    // Checking if vector is empty or not
    if (v.empty())
        cout << "Empty";
    else
        cout << "Not Empty";
    return 0;
}

Output
Vector is Empty

Explanation: The vector empty() function will return true, if the std::vector is empty, otherwise returns false.

C++ provides more ways to check whether the vector is empty or not. They are as follows:

Using Vector size()

The vector size() method returns the number of elements present in the vector, so if the vector is empty then size() function will return 0.

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

int main() {
    vector<int> v;

    // Checking if vector is empty or not
    if (v.size() == 0)
        cout << "Empty";
    else
        cout << "Not Empty";
    return 0;
}

Output
Vector is Empty

Using Iterator

The vector begin() and vector end() returns the iterator to the beginning and the end of the vector respectively. If the vector is empty, both the iterators will be equal.

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

int main() {
    vector<int> v;

    // Checking if vector is empty or not
    if (v.begin() == v.end())
        cout << "Empty";
    else
        cout << "Not Empty";
    return 0;
}

Output
Vector is Empty

Next Article
Article Tags :
Practice Tags :

Similar Reads