-1

我需要帮助!我正在做一个结构数组的堆,我的 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);
}
4

1 回答 1

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);
    }
}
于 2013-06-05T23:41:25.483 回答