奇数C ++运算符优先级

时间:2013-09-10 18:30:54

标签: c++

有人可以向我解释为什么这有意义(请注意heapvector<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()) {} 

然而:

// Code does enter this block when heap.size() is 0? Why?
while (leftChild < (heap.size() - 1) {}

我感觉到这种情况正在发生,因为-1在某种程度上被解释为'真实',但我不明白leftChild(默认情况下1是怎样的小于0-1

1 个答案:

答案 0 :(得分:5)

heap.size()会返回std::size_t,其类型定义为unsigned int((unsigned int)0)-1仍然是unsigned int,等于unsigned int的最大值。因此,leftChild将始终小于heap.size() - 1,除非它恰好等于0xFFFFFFFF(对于32位整数)。