While debugging something, I saw the STL vector::empty() implementation:
bool empty() const {return (size() == 0); }
I believe, whenever we are probing the emptiness of vector it is always recommended to use empty over size(). But seeing that implementation, I am wondering, what is the benefit of doing so? Instead, there is a function call overhead in calling empty as it internally calls size()==0.
I thought empty() may be helpful in case of list as size() doesn't guarantees the constant time in list. To verify my assumption, I checked the list implementation and surprisingly, found the same implementation in list as well,
return (size() == 0);
I am bit confused now. If empty internally uses size() then why should we prefer empty over size() ?
If the vector container is empty what will size() and empty() returns? Size will return 0 and empty will return 1 because if there is no element in the vector the size of that vector will be 0 and empty will be true so it will return 1.
C++ Vector empty() empty() returns true if the vector is empty, or false if the vector is not empty.
prefix == prefix) { find =1; return map[i]. sufix; //sufix is a vector from a class called "Pair. h" } } if(find==0) { //return an empty vector. } }
To get the size of a C++ Vector, you can use size() function on the vector. size() function returns the number of elements in the vector.
Because if you switch from std::vector to std::list or other container, it may be different.
For example some implementations of std::list::size
take O(n)
and not O(1)
.
You would need to write the condition out everytime you use size()
. It's convenient to use empty()
. This is of course, provided you don't switch containers. As others have pointed out, it is upto the implementation to use size()
in empty()
or not. However, the standard does guarantee that: empty()
is a constant-time operation for all standard containers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With