Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

用STL实现堆容器

$
0
0

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

作者:ClamReason 发表于2013-12-22 0:46:11 原文链接
阅读:130 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>