我需要帮助!我正在做一个结构数组的堆,我的reheap down算法似乎是错误的,我已经尝试了所有我知道的东西,这种东西在没有结构,只有数组时有效。所以这是错误:
main.cpp: In function 'void reheapDown(hitna**, int, int&)':
main.cpp:88: error: invalid types 'hitna**[std::ios_base& ()(std::ios_base&)]' for array subscript
main.cpp:89: error: invalid conversion from 'std::ios_base& (*)(std::ios_base&)' to 'int'
和代码:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct hitna{
string ime;
int broj;
};
void unos(hitna *heap[50], int &last);
void reheapUp(hitna *heap[], int &last);
void exchange(hitna *&x, hitna *&y);
void reheapDown(hitna *heap[],int parent, int &last);
void obrada(hitna *heap[], int &last);
int main(){
hitna *heap[50]={0};
int last = -1;
int odg;
do{
cout<<"- - - I Z B O R N I K - - -";
cout<<"\n\n1)Unos pacijenata\n";
cout<<"2)Obrada pacijenata\n";
cout<<"3)Ispis pacijenata\n";
cout<<"4)Izlaz\n";
cout<<"\nOdabir: ";
cin>>odg;
switch(odg){
case 1:
unos(heap, last);
break;
case 2:
obrada(heap, last);
break;
case 3:
for (int i=0;i<=last;i++){
cout<<heap[i]->ime<<" "<<heap[i]->broj<<endl;
}
case 4:break;
default:
break;
};
}while(odg!=4);
return 0;
}
void exchange(hitna *&x, hitna *&y){
hitna *t = x;
x=y;
y=t;
}
void unos(hitna *heap[50], int &last){
last++;
heap[last]=new hitna;
cout<<"IME: ";cin>>heap[last]->ime;
cout<<"BROJ: ";cin>>heap[last]->broj;
reheapUp(heap, last);
}
void reheapUp(hitna *heap[], int &last){
int parent=(last-1)/2;
if (heap[parent]->broj < heap[last]->broj){
exchange(heap[parent], heap[last]);
reheapUp(heap, parent);}
}
void reheapDown(hitna *heap[],int parent, int &last){
int left = 2 * parent + 1;
if(left<=last){
int child = left;
if(left+1<=last) int right = child+1;
if ((heap[right]->broj) > (heap[left]->broj)) //THIS IS WRONG
{child = right;} //THIS ALSO
if (heap[parent]->broj < heap[child]->broj){
exchange(heap[parent], heap[child]);
reheapDown(heap, child, last);
}
}
}
void obrada(hitna *heap[], int &last){
if(last<0) {return;}
exchange(heap[0], heap[last]);
last--;
reheapDown(heap, 0, last);
}
答案 0 :(得分:1)
right
的范围不正确。
if(left+1<=last) int right = child+1;
标识符right
仅存在于此if块中,因此您无法在外部使用它。在这种情况下,您需要确定哪些是正确的。如果条件left+1<=last
不成立,您是否仍应执行函数中的剩余代码?如果是这样,您需要在right
之外声明(与left
相同的范围级别),并为其指定适当的值。
我希望你想要这样的东西:
if(left+1 <= last) {
int child = left;
int right = left+1;
if ((heap[right]->broj) > (heap[left]->broj))
child = right;
if (heap[parent]->broj < heap[child]->broj) {
exchange(heap[parent], heap[child]);
reheapDown(heap, child, last);
}
}