Checking whether a vector is empty

Suppose I have a std::vector say Vector

Now after performing some operations on the vector(either insertion or deletion) I want to check if the vector is empty and on the basis of that I want to perform some operations.

Which approach is better

Approach 1

if (Vector.size() == 0){ /* operations */ }

Approach 2

if (Vector.empty()) { /* operations */ }

Which is a better approach, 1 or 2?


Solution 1:

v.size() == 0 says "I'm comparing the size", but does so to check whether the container empty. There's a small algorithm to digest (very small, as it only consists of a comparison) before you know what it does.
OTOH, v.empty() does exactly what it says: it checks whether v is empty.
Due to this, I clearly prefer #2, as it does what it says. That's why empty() was invented, after all.

But there's also an algorithmic reason to prefer empty(): If someone later changes std::vector into a std::list, v.size() might have O(n). (In C++ 03 it's guaranteed to be O(1) for std::vector, but not for std::list. According to James' comment to Prasoon's answer it will be O(1) for all containers in C++1x.)

Solution 2:

Approach (2) would be better because empty() always runs in a constant time [i.e O(1)] irrespective of the container type.

size() too runs in O(1)[for std::vector] although it might run in O(n) for std:list [thats implementation defined to be honest]

In Effective STL[Item 4] Scott Meyers says

You should prefer the construct using empty, and the reason is simple: empty is a constant-time operation for all standard containers, but for some list implementations, size takes linear time.

.....

No matter what happens, you can't go wrong if you call empty instead of checking to see if size() == 0. So call empty whenever you need to know whether a container has zero elements.