这容器内部使用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
请按任意键继续. . .
本文介绍了一个使用vector作为内部容器的简单堆实现。该堆仅提供了empty、pop和push三种操作,通过实例演示了如何利用这些操作进行元素的插入与删除,并保持堆的性质。
198

被折叠的 条评论
为什么被折叠?



