龙小爱编程

导航

 

堆:堆不是STL中的容器组件,堆有分为大根堆和小根堆,堆的底层实现可以用优先队列进行实现。底层的容器实际上是一个vector。在C++数据结构中,堆也可用数组来实现。对于使用C++的开发人员来说,stl组件的algorithm.h头文件中提供了一下操错堆的方法。具体的方法如下:

make_heap(),push_heap(),pop_heap();sort_heap()
具体示例代码如下:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main(int argc, char *argv[]) {
	std::cout<<"In this case we'll show the operator of heap"<<std::endl;
	int iArray[]={1,2,3,4,5,6,7};
	std::vector<int> myvec(iArray,iArray+7);
	std::cout<<"show the elements of myvec...."<<std::endl;
	for(std::vector<int>::iterator it = myvec.begin();it != myvec.end();it++){
		std::cout<<*it<<" ,";
	}
	std::cout<<"\n"<<"now we'll create the heap"<<endl;
	make_heap(myvec.begin(), myvec.end());
	for(std::vector<int>::iterator it = myvec.begin();it != myvec.end();it++){
		std::cout<<*it<<" ,";
	}
	std::cout<<"\n"<<"now we'll pop the element...."<<std::endl;
	pop_heap(myvec.begin(), myvec.end());
	myvec.pop_back();
	for(std::vector<int>::iterator it = myvec.begin();it != myvec.end();it++){
		std::cout<<*it<<" ,";
	}
	std::cout<<"\n"<<"now we'll push the element...."<<std::endl;
	myvec.push_back(123);
	push_heap(myvec.begin(), myvec.end());
	for(std::vector<int>::iterator it = myvec.begin();it != myvec.end();it++){
		std::cout<<*it<<" ,";
	}
	std::cout<<"\n"<<"now we'll sort the element...."<<std::endl;
	sort_heap(myvec.begin(), myvec.end());
	for(std::vector<int>::iterator it = myvec.begin();it != myvec.end();it++){
		std::cout<<*it<<" ,";
	}
	std::cout<<"\n"<<"now the example is end...."<<std::endl;
	return 0;
}

posted on 2017-03-21 21:06  龙小爱编程  阅读(151)  评论(0编辑  收藏  举报