[英]parent in a heap has children or not
I am trying to check a Max-Heap to see whether a parent has children or not. 我正在尝试检查Max-Heap,以查看父母是否有孩子。 My heap is implemented as a vector.
我的堆被实现为向量。 At first i wrote a function bool hasChildren(int loc) loc is the location of the parent in the heap.
最初,我编写了一个函数bool hasChildren(int loc)loc是父对象在堆中的位置。 my main conditional was:
我的主要条件是:
if(heap[2*loc + 1] == NULL && heap[2*loc + 2] == NULL) //if there are children
The problem is that you cannot check out of bounds indices... I thought of pointer arithmetic but that is invalid too. 问题是您无法检查边界索引...我想到了指针算术,但这也是无效的。 Does anybody have a suggestion for how to check whether a parent in a heap has children?
有人对如何检查堆中的父母是否有孩子有建议吗?
thanks! 谢谢!
Do you know how large heap
was malloc
ed to be? 你知道如何大
heap
是malloc
ED是? If so, just make sure that 2*loc+1 and 2*loc+2 are within that range. 如果是这样,只需确保2 * loc + 1和2 * loc + 2在该范围内即可。 If
heap
was malloc
ed to have N elements, make sure that 2*loc+1 and 2*loc+2 are less than N: 如果
heap
是malloc
编有N个元素,确保2 * LOC + 1和2 * LOC + 2小于N:
if(((2*loc+1 < N) && (heap[2*loc + 1] == NULL)) &&
((2*loc+2 < N) && (heap[2*loc + 2] == NULL)))
The problem is that you cannot check out of bounds indices
问题是您无法检查出界索引
If this is an std::vector
, you can use its at
member function and catch the std::out_of_range
exception. 如果这是
std::vector
,则可以使用其at
成员函数并捕获std::out_of_range
异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.