Reputation: 1373
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?
Upvotes: 2
Views: 352
Reputation: 234795
For some containers, size()
might be an O(N) traversal, whereas empty()
is probably O(1). But do note that C++11 and onwards requires all standard containers' size()
and empty()
to be O(1).
So if you want to write container-agnostic code, then plump for empty()
if you can.
Finally did you want size() > 0
?
Upvotes: 1
Reputation: 26186
bool is_nonempty_notgood = (v.size() >= 0); // Try to avoid this
That should be a >
, not a >=
.
first, size() is unsigned, which may sometimes cause problems;
Sizes being unsigned or not is a recurrent topic in C/C++, see e.g. Why is size_t unsigned?
In general, unsigned integers have some pitfalls. If you don't want to deal with those, simply use signed integers (be it a size or not).
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.
Imagine I give you a deck. At a quick glance, you know there is at least one card in it (!v.empty()
), right?
However, if I ask you to count exactly how many cards are there (v.size()
), it will take you a while.
Upvotes: 4