How to Check if a Vector is Empty in C++?
Last Updated :
21 Feb, 2024
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++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > vector1;
if (vector1.empty()) {
cout << "Vector is empty" << endl;
}
else {
cout << "Vector is not empty" << endl;
}
return 0;
}
|
Time Complexity : O(1)
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...