棧結構:
heap.h
#ifndef HEAP_H
#define HEAP_H
#include <iostream>
template<typename T>
class Heap
{
private:
static const int max =50;
T heap[max];
int top;
public:
Heap();
~Heap(){};
bool Isempty();
bool Isfull();
bool pop();
bool push(const T & p);
void show();
};
#endif
heap.cpp
#include "heap.h"
template<typename T>
Heap<T>::Heap()
{
top =0;
}
template<typename T>
bool Heap<T>::Isempty()
{
return top == 0;
}
template<typename T>
bool Heap<T>::Isfull()
{
return top == max;
}
template<typename T>
bool Heap<T>::push(const T & p)
{
if(!Isfull())
{
heap[top] = p;
top++;
return true;
}else return false;
}
template<typename T>
bool Heap<T>::pop()
{
if(!Isempty())
{
top--;
return true;
}else return false;
}
template<typename T>
void Heap<T>::show()
{
if(!Isempty())
{
std::cout<<"堆棧爲:"<<std::endl;
for(int i =top-1;i>=0;i--)
std::cout<<heap[i]<<" ";
std::cout<<std::endl;
}else std::cout<<"堆棧已空!"<<std::endl;
}
測試代碼:testStruct.cpp
#include "heap.h"
#include"heap.cpp"
#include <stdlib.h>
void main()
{
Heap<int> heap;
const int m =10;
int n =rand();
for(auto i=0;i<m;i++)
heap.push(rand()%100);
heap.show();
heap.pop();
heap.show();
heap.push(5);
heap.show();
system("pause");
}
這裏出現了點小問題 我加上了#include“heap.cpp”
問題原因是:現在的編譯器幾乎都不支持模板分離編譯,也就是不支持 export關鍵字,所以你要麼把cpp裏的代碼全都寫到.h中去,要麼在main函數中#include 對應的cpp
我把模板去掉也去掉#include“heap.cpp”調試正確。算是個問題吧