0

Can someone explain to me why this makes sense (note that heap is a vector<int>):

// Heap Sort
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:

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

4

1 回答 1

5

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

于 2013-09-10T18:37:07.263 回答