这容器内部使用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
请按任意键继续. . .

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐