Open In App

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

Last Updated : 21 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. In this article, we will learn how to check if a vector is empty in C++.

Example

Input:
vector1 = { 1 , 2 , 3 , 4}
Output:
false

Input:
vector2 = {}
Output:
True

Checking Whether a Vector is Empty in C++

We can check if a vector is empty in C++ by using std::vector::empty() method. This function returns true if the std::vector is empty and returns false if the vector is not empty.

C++ Program to Check if a Vector is Empty

C++




// C++ Program to Check if a Vector Is Empty
#include <iostream>
#include <vector>
using namespace std;
  
// Driver Code
int main()
{
    vector<int> vector1;
    // return  if the vector is empty
    if (vector1.empty()) {
        cout << "Vector is empty" << endl;
    }
    else {
        // return if vector is not empty
        cout << "Vector is not empty" << endl;
    }
  
    return 0;
}


Output

Vector is empty

Time Complexity : O(1)
Space Complexity: O(1)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads