The Wayback Machine - https://web.archive.org/web/20250304091939/https://www.geeksforgeeks.org/vector-empty-in-cpp-stl/
Open In App

Vector empty() in C++ STL

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

In C++, vector empty() is a built-in method used to check whether the given vector is empty or not. In this article, we will learn about vector empty() method in C++.

Let’s take a look at an example that illustrates the vector empty() method:

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

int main() {
    vector<int> v = {11, 23, 45, 9};

    // Check if the vector is empty
    if (v.empty()) {
        cout << "Empty";
    } else {
        cout << "Not empty";
    }

    return 0;
}

Output
Not empty

This article covers the syntax, usage, and common examples of the vector empty() method in C++ STL, along with some interesting FAQs.

Syntax of Vector empty()

The vector empty() is defined inside std::vector class defined inside <vector> header file.

v.empty();

Parameter:

  • This function does not take any parameter.

Return Value:

  • Returns true if the vector is empty.
  • Returns false if the vector is not empty.

Examples of Vector empty()

The below example demonstrate the practical use of vector empty() method:

Check if a Vector is Empty

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

int main() {
    vector<int> v;

    if (v.empty()) {
        cout << "Empty";
    } else {
        cout << "Not Empty";
    }

    return 0;
}

Output
Empty

Safely Accessing the First Element of the Vector

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

int main() {
    vector<int> v = {11, 23, 45, 9};

      // Checking whether a vector is empty before using
      // vector front() method
    if (!v.empty()) {
        cout << v.front();
    } else {
        cout << "Vector is empty";
    }

    return 0;
}

Output
11

Explanation: Calling vector back() on an empty vector causes undefined behaviour. To prevent this, vector empty() is used.

Vector empty() in C++ – FAQs

What is the difference between empty() and clear()?

The vector empty() checks if a vector has any elements while vector clear() removes all elements from the vector, making it empty.

Is vector empty() preferred over vector size()? If yes, then why?

Yes, vector empty() method is preferred of vector size() if you just want to check the existence of elements in vector. The main reason for this is that C++ standard guarantees the constant time complexity for vector empty() (or in general, all containers’ empty()) method but the time complexity of the vector size() (or any other STL container) is not guaranteed. It is left on the compiler vendor’s choice.


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg