The Wayback Machine - https://web.archive.org/web/20250328085415/https://www.geeksforgeeks.org/how-to-check-if-vector-is-empty-in-cpp/
Open In App

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

Last Updated : 18 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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

Frequently Asked Questions – FAQs

Is vector capacity() reliable for checking if a vector is empty?

Not always. If v.capacity() == 0, then vector is empty and unallocated, but if elements were added and then removed, vector capacity() may still be greater than zero even when size() is zero.

What is time complexity for checking if vector is empty or not?

The time complexity for checking if the vector is empty or not is O(1).

Which is best method to check if a vector is empty or not?

The best method to check if vector is empty or not is by using vector empty() function.


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg