遍历最小堆时获取垃圾值
Getting garbage values when traversing min-heap
这是我的遍历方法:
void heapTraversal(){
for(int i = 0; i<maxsize; i++){
cout << "Current value is : " << hipa[i] << endl;
if(hipa[(2*i)+1]){
cout << "Left child is : " << hipa[(2*i)+1] << endl;
}
else{
cout << "Left child does not exist" << endl;
}
if(hipa[(2*i)+2]){
cout << "Right child is : " << hipa[(2*i)+2] << endl;
}
else{
cout << "Right child does not exist" << endl;
}
这是我的输出:
Current value is : 7
Left child is : 9
Right child is : 17
Current value is : 9
Left child is : 15
Right child is : 12
Current value is : 17
Left child is : 25
Right child is : 22
Current value is : 15
Left child is : 1769234787
Right child does not exist
Current value is : 12
Left child does not exist
Right child does not exist
Current value is : 25
Left child does not exist
Right child is : 1852112910
Current value is : 22
Left child is : 1395618676
Right child is : 1701994856
它似乎工作正常,但我拥有所有这些我不应该拥有的垃圾值,我无法确定问题所在。
我怀疑控制结构有问题,我的逻辑是否正确,还是我应该使用 else if 语句?
即使您在答案中发布了"修复程序",您也会在heap_size >= (maxsize/2)
时遇到同样的问题。您必须检查计算的左右子索引。更正的代码:
void heapTraversal(){
for(int i = 0; i<heap_size; i++){
cout << "Current value is : " << hipa[i] << endl;
int left = (2*i)+1;
if(left < heap_size && hipa[left]){
cout << "Left child is : " << hipa[left] << endl;
}
else{
cout << "Left child does not exist" << endl;
}
int right = left+1;
if(right < heap_size && hipa[right]){
cout << "Right child is : " << hipa[right] << endl;
}
else{
cout << "Right child does not exist" << endl;
}
我已经通过将 for 循环参数从 maxsize 更改为 heap_size 来解决此问题。 maxsize 应该是堆的容量,而 heap_size 是堆的当前大小。我为好奇的人添加了类声明的其余部分。
class minHeap{
int *hipa;
int maxsize;
int heap_size;
public:
minHeap(int size);
void minHeapbuild(int );
int root(int i){
return (i-1)/2;
}
int left(int i){
return (2*i+1);
}
int right(int i){
return (2*i+2);
}
int extractRoot();
void decreaseKey(int i, int newKey);
void deleteKey(int key);
void addKey(int key);
int getRoot(){
return hipa[0];
}
}
相关文章:
- 有什么方法可以遍历结构吗
- 在循环中按顺序遍历成员变量
- 遍历模板参数
- 在遍历处理程序的向量时注册和注销处理程序
- C++RapidXml-使用first_node()遍历以修改XML文件中节点的值
- 遍历并行数组以确定C++中的最大数字
- 遍历顺序由 std::文件系统directory_iterator给出
- 遍历链表时的无限循环
- 遍历unordered_map向量
- 从预序遍历构造 bst 的 c++ 和 python 解决方案之间的区别
- 如何遍历多个地图并获取它们的值? - C++
- Rapidjson 遍历并获取复杂 JSON 对象成员的值
- 遍历最小堆时获取垃圾值
- 遍历区域并在 OpenCV 中获取平均像素值
- 遍历 std::string 时如何获取没有数字的字符?
- C++遍历对象并获取其地址
- 如何在不遍历优先级队列的情况下获取该队列的最后一个元素
- 遍历所有字段并在 protobuf 消息中获取它们的值
- 在不遍历文件内容的情况下从文件中获取信息
- 反向遍历一个向量并获取相邻元素的值