gpt4 book ai didi

c++ - 尝试堆插入时访问冲突写入位置

转载 作者:行者123 更新时间:2023-11-28 07:01:49 25 4
gpt4 key购买 nike

#include <iostream>
using namespace std;



int getParent(int);
int getLeftChild(int);
int getRightChild(int);
void swap(int&, int&);
void heapify(int A[], int);
void build_heap(int A[]);
void printArray(int A[], int);
void heapInsert(int A[], int);

int main()

{
int parent;
int right;
int left;
int A[10]={4,1,3,2,16,9,10,14,8,7};



heapify(A,3);

cout << "Print Array A:" << endl;
printArray(A, 10);
cout << endl;
build_heap(A);
parent=getParent(5);
left=getLeftChild(3);
right=getRightChild(3);
cout<<"Parent of node 5 is the node " << parent << endl;
cout<<"Left child of node 3 is the node " << left << endl;
cout<<"Left child of node 3 is the node " << right <<endl << endl;
cout << "Print Heap A:" << endl;
printArray(A, 10);
cout << endl;
cout << "After inserting the number 20:" << endl;
heapInsert(A, 20);
build_heap(A);
printArray(A, 11);
cout << endl;
cout << "After inserting the number 17:" << endl;
heapInsert(A, 17);
build_heap(A);
printArray(A, 12);

system("pause");
return 0;


}

void heapInsert(int A[], int Item)
{
int i = 10;
A[i] ++;
i = A[i];
while (i > 1 && A[getParent(i)] < Item)
{
A[i] = A[getParent(i)];
i = getParent(i);
}
A[i] = Item;
}

当我尝试增加堆的大小时并使用 heapInsert 函数调用插入新值时出现问题。我的所有其他功能都运行良好,但我不知道从这里到哪里去。

最佳答案

int A[10]={4,1,3,2,16,9,10,14,8,7};

int i = 10;
A[i] ++;

数组 A 的最大索引是 9。

关于c++ - 尝试堆插入时访问冲突写入位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22338332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com