Check whether a vector is empty in C++
This post will discuss how to check whether a vector is empty in C++. In other words, check whether its size is 0.
1. Using std::vector::empty function
The standard solution to check whether a vector is empty in C++ is to use the empty() function from the std::vector class. This function returns a boolean value that indicates whether the vector has any elements or not. It returns true if the vector is empty; false otherwise. The typical invocation for this function would look like:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <vector> int main() { std::vector<int> v; bool isEmpty = v.empty(); std::cout << std::boolalpha << isEmpty << std::endl; // true return 0; } |
2. Using std::vector::size function
Another way to check whether a vector is empty in C++ is to use the size() function from the std::vector class. This function returns an integer value that indicates how many elements the vector has. To use the size() function to check whether a vector is empty in C++, we need to compare the returned value with zero. If the returned value is zero, then the vector is empty. If the returned value is positive, then the vector has some elements. For example:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <vector> int main() { std::vector<int> v; bool isEmpty = v.size() == 0; std::cout << std::boolalpha << isEmpty << std::endl; // true return 0; } |
3. Using std::vector::begin and std::vector::end functions
These methods return iterators that point to the first and the last element of the vector, respectively. We can compare these iterators to check whether the vector is empty or not. If they are equal, then the vector is empty. If they are not equal, then the vector has some elements. This function require us to include the <iterator> header.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <vector> int main() { std::vector<int> v; bool isEmpty = v.begin() == v.end(); std::cout << std::boolalpha << isEmpty << std::endl; // true return 0; } |
That’s all about checking whether a vector is empty in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)