include
include
using namespace std;
class NoMoreSpace: public exception { char *msg; public: NoMoreSpace(): msg("No More Space"){} const char *what() const throw() { return msg; } };
template class Heap { int count; T *items; int size; public: Heap(int size) { count=0; items=new T[Heap::size=size]; } void insert (const T &element); T &operator[](int i) { return items[i]; } const T &operator[](int i) const { return items[i]; } void print(); };
template void Heap::insert(const T & elem) { if (count>=size) throw NoMoreSpace(); int curIndex=count++; int parentIndex; while(curIndex > 0 && elem < items[parentIndex=(curIndex-1)/2]) { items[curIndex]=items[parentIndex]; curIndex=parentIndex; } items[curIndex]=elem; }
template void Heap::print() { for (int i=0; i<count; i++) cout << items[i] << ' ' << endl; }
int main() { Heap hp(1000); try { hp.insert(3); hp.insert(7); hp.insert(1); hp.insert(4); hp.insert(2); hp.insert(0); } catch (NoMoreSpace &ex) { cout << "Got an exception: " << ex.what() << endl; } hp.print(); }