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:

Download  Run Code

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:

Download  Run Code

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.

Download  Run Code

That’s all about checking whether a vector is empty in C++.