我首先写了一个heap类;
下面是一个不完整的heap类:
#include <iostream>
#ifndef _HEAP_H_
#define _HEAP_H_
using namespace std;
class heap
{
public:
heap()
{
}
int HeapPar(int i)
{
return i/2;
}
int HeapLeft(int i)
{
return 2*i;
}
int HeapRight(int i)
{
return 2*i+1;
}
template <class T>
int getArrayLen(T& array)
{//使用模板定义一个函数getArrayLen,该函数将返回数组array的长度
return (sizeof(array) / sizeof(array[0]));
}
void InHeat(int A[]);
void MaxHeapify(int i);
int* Pheap;
int HeapSize;
~heap()
{
delete [] Pheap;
}
}
#endif
注意到没有,heap类的定义后面我没有写分号
接下来是两个成员函数的实现文件
#include"heap.h"
void heap::InHeat(int A[])
{
HeapSize=getArrayLen(A);
Pheap=new int[HeapSize];
}
#include"heap.h"
void heap::MaxHeapify(int i)
{
int l,r,largest;
int temp;
l=HeapLeft(i);
r=HeapRight(i);
if((l<=HeapSize)&&(Pheap[l-1]>Pheap[i-1]))
{
largest=l;
}
else
{
largest=i;
}
if((r<=HeapSize)&&(Pheap[r-1]>Pheap[largest-1]))
{
largest=r;
}
if(largest!=i)
{
temp=Pheap[i-1];
Pheap[i-1]=Pheap[largest-1];
Pheap[largest-1]=temp;
heap::MaxHeapify(largest);
}
}
下面是对上面两个成员函数文件单独编译的结果:
由于类的定义少了个分号,所以会出现上面的编译错误。
另外刚开始的时候,我没有把int getArrayLen(T& array)写在类里面作为类的成员函数
而是作为全局函数在类外定义的,所以当我用类的成员函数调用它时,老报错
所以我总结了一下,类的成员函数不能调用全局函数的。
下面是完整的heap类
#include <iostream>
#ifndef _HEAP_H_
#define _HEAP_H_
using namespace std;
class heap
{
public:
heap()
{
}
int HeapPar(int i)
{
return i/2;
}
int HeapLeft(int i)
{
return 2*i;
}
int HeapRight(int i)
{
return 2*i+1;
}
template <class T>
int getArrayLen(T& array)
{//使用模板定义一个函数getArrayLen,该函数将返回数组array的长度
return (sizeof(array) / sizeof(array[0]));
}
void InHeat(int A[]);
void MaxHeapify(int i);
void BuildMapHeap();
int* Pheap;
int HeapSize;
~heap()
{
delete [] Pheap;
}
};
#endif
#include"heap.h"
void heap::MaxHeapify(int i)
{
int l,r,largest;
int temp;
l=HeapLeft(i);
r=HeapRight(i);
if((l<=HeapSize)&&(Pheap[l-1]>Pheap[i-1]))
{
largest=l;
}
else
{
largest=i;
}
if((r<=HeapSize)&&(Pheap[r-1]>Pheap[largest-1]))
{
largest=r;
}
if(largest!=i)
{
temp=Pheap[i-1];
Pheap[i-1]=Pheap[largest-1];
Pheap[largest-1]=temp;
heap::MaxHeapify(largest);
}
}
#include"heap.h"
void heap::InHeat(int A[])
{
HeapSize=getArrayLen(A);
Pheap=new int[HeapSize];
}
#include"heap.h"
void heap::BuildMapHeap()
{
for(int i=heap::HeapSize/2;i>=1;i--)
{
heap::MaxHeapify(i);
}
}