ошибка компиляции в HeapTree - PullRequest
0 голосов
/ 12 марта 2012

вот мой код для реализации HeapTree

 #include<iostream>
#include<assert.h>
using namespace std;

template <class Elem>
class HeapTree
{
  public:
    HeapTree(int MaxSize=500);
    HeapTree(const HeapTree<Elem> &OtherTree);
    HeapTree(Elem *Array, int ElemNum, int MaxSize);
    Elem *Sort(void); // Built-in HeapSort Algorithm
    ~HeapTree(void);

    bool Add(const Elem &Item);  // Add the Item to Heap
    Elem Remove(void);           // Remove and return Item from Heap

    inline int GetSize(void);    // Returns the number of nodes in the Heap

protected:
        Elem *Data;//actual data array
        int currentnum;
        const int Max_size;
        void shiftup(int node);
        void shiftdown(int node);
        inline int parent(int node);
 inline  int leftchild(int node);

};
template <class Elem>
inline int HeapTree<Elem>::parent(int node){
assert(node>0);
return (node-1)/2;

}
template <class Elem>
inline int HeapTree<Elem>::leftchild(int node){
 return (node*2)+1;
}
//HeapTree construction
template<class Elem>
HeapTree<Elem>::HeapTree(int maxsize)
:Max_size(maxsize)
{
Data=new Elem[Max_size];
currentnum=0;

}
//HeapTree copy construction function
template<class Elem>
HeapTree<Elem>::HeapTree(const HeapTree<Elem> &other)
        :Max_size(other.Max_size)

{
        Data=new Elem[Max_size];
        int  current=other.currentnum;
         for (int i=0;i<other.currentnum;++i)
                 Data[i]=other.Data[i];


}
template <class Elem>
HeapTree<Elem>::HeapTree(Elem *Array,int ElemNum,int Maxsize)
:Max_size(Maxsize)
{
Data=new Elem[Max_size];
currentnum=ElemNum;
 for (int i=0;i<ElemNum;++i)
         Data[i]=Array[i];
  for (int i=parent(currentnum-1);i>=0;--i)
          shiftdown(i);

}
// Built-in Heap Sort algorithm
template<class Elem>
Elem *HeapTree<Elem>::Sort(void)
{
Elem * newArray=new Elem[currentnum];
for (int i=currentnum-1;i>=0;--i)
{
newArray[i]=Remove();


}
 return newArray;
}
//HeapTree destruction function
template <class Elem>
HeapTree<Elem>::~HeapTree(void)
{
if (Data)
 delete Data;

}
template <class Elem>
bool HeapTree<Elem>::Add(const Elem &item)
{
if (currentnum>=Max_size)
 return false;
Data[currentnum]=item;
shiftup(currentnum++);
return true;

}
//remove function
template <class Elem>
Elem HeapTree<Elem>::Remove(void)
{
assert(currentnum>0);
Elem temp=Data[0];
Data[0]=Data[--currentnum];//replace with last element;
shiftdown(0);
return temp;


}
// GetSize() function
template<class Elem>
inline int HeapTree<Elem>::GetSize(void)
{
return currentnum;
}
//shift up
template<class Elem>
void HeapTree<Elem>::shiftup(int node)
{
int current=node;
int Parent=parent(current);
Elem item=Data[current];
while(current>0)
{
if(Data[Parent]<item)
{
Data[current]=Data[Parent];
current=Parent;
Parent=parent(current);

}
else
break;

}
Data[current]=item;
}
// ShiftDown() function
template <class Elem>
void HeapTree<Elem>::shiftdown(int node)
{
int current=node,
child=leftchild(current);
Elem item=Data[current];
while(child<currentnum)
{
if (child<(currentnum-1))
if(Data[child]<Data[child+1])
++child;
if(item<Data[child]){
Data[current]=Data[child];
current=child;
child=leftchild(current);
}
else
break;

}

Data[current]=item;
}
int main(){
        int a[]={12,31,10,6,4,7,9,8,0,11};
        int n=sizeof(a)/sizeof(a[0]);
        HeapTree<int>hp(a,n,n);
        hp.Sort();
        cout<<hp.Remove()<<" ";

return 0;
}

, но когда я его запускаю, он пишет ошибку компиляции, я думаю, что в main () месте, где я не создал экземпляр HeapTree правильно, пожалуйста, помогитемне определить, что не так с этим кодом

Ответы [ 2 ]

2 голосов
/ 12 марта 2012

HeapTree::Sort вызывает HeapTree::Remove, пока ваша куча не будет отсортирована. После последнего вызова Remove внутри Sort значение currentnum равно 0, поэтому другой вызов Remove не может подтвердить указанное вами условие. (currentnum>0)

Примечание: Я считаю, что вы не должны очищать дерево, сортируя его!

1 голос
/ 12 марта 2012

Отсутствие отступов делает ваш код немного сложным для отслеживания, но, похоже, ваш Sort метод очищает дерево и возвращает вновь распределенный массив всех элементов.

Когда вы попадаете на Remove в main, дерево уже пусто, поэтому ваше утверждение не выполняется.

Вы действительно хотите очистить дерево при сортировке?

...