Reputation: 11439
Why does the following make sense (note that heap
is a vector<int>
)?
// Heapsort
int parent = 0;
int leftChild = (parent * 2) + 1;
int rightChild = (parent * 2) + 2;
// This conditional works fine. Code doesn't enter block when heap.size() is zero.
while (leftChild < heap.size()) {}
However:
// The code does enter this block when heap.size() is 0? Why?
while (leftChild < (heap.size() - 1) {}
I get the sense that this is occurring because -1
is somehow being interpreted as 'truthy', but I don't understand how leftChild
(which by default is 1
can ever be less than 0
or -1
.
Upvotes: 0
Views: 90
Reputation: 15870
heap.size()
returns an std::size_t
, which is typedef'd to be an unsigned int
. ((unsigned int)0)-1
is still an unsigned int
that is equal to the maximum value for an unsigned int
. Thus, leftChild
will always be less than heap.size() - 1
unless it happens to be equal to 0xFFFFFFFF
(for 32-bit ints).
Upvotes: 5