How to Check if a Vector is Empty in C++?
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)
Contact Us