用STL实现堆容器

来源:互联网 发布:网络清洁器 编辑:程序博客网 时间:2024/05/17 10:55

这容器内部使用vector,外部只提供empty,pop,push,三个操作。其中pop操作剔除顶,并返回顶部元素

#include <iostream>#include <vector>#include <algorithm>using namespace std;template<typename T>class heap{public:bool empty(){ return data_.empty();}T pop(void );void push(const T& t);private:vector<T> data_;};template<typename T>void heap<T>::push(const T& t){data_.push_back(t);make_heap(data_.begin(),data_.end());}template<typename T>T heap<T>::pop(void){T t=data_.front();data_.erase(data_.begin());make_heap(data_.begin(),data_.end());return t;}int main(){heap<int> h;for (int i=1;i<11;i++){h.push(i);}while (!h.empty()){cout<<h.pop()<<endl;}}





10
9
8
7
6
5
4
3
2
1
请按任意键继续. . .

0 0
原创粉丝点击