Search code examples
c++stlsize

size() Vs empty() in vector - why empty() is preferred?


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() ?


Solution

  • 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.