写一些结构体的代码(stack,queue,现行表,二叉树,图模板 持续更新……)

来源:互联网 发布:qt5 gui编程 编辑:程序博客网 时间:2024/05/23 17:48

栈结构:

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”调试正确。算是个问题吧

 

0 0