I read in a tutorials said:
bool is_nonempty_notgood = (v.size() > 0); // Try to avoid this
bool is_nonempty_ok = !v.empty();
The explanation I failed to understand:
first, size()
is unsigned, which may sometimes cause problems;
Second, it’s not a good practice to compare v.size()
to zero if you want to know whether the container is empty.This is because not all the containers can report their size in O(1)
, and you definitely should not require counting all elements in a double-linked list just to ensure that it contains at least one.
Could someone provide some examples and more details?