堆函数
来源:互联网 发布:游戏运营数据分析 编辑:程序博客网 时间:2024/06/05 20:05
一。封装一个泛型堆
先展示一下这一套堆函数的易用性,紧跟后面再详细阐述他们的用法。
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
using namespace std ;
//接口说明
//bool empty() 判空
//size() 堆大小
//clear() 清空堆
//push(const T& x) 推入元素x
//const T& top() 堆顶元素
//pop() 弹出堆顶
template<class T , class Compare = less<T> >
class myheap{
private:
vector<T> data ;
Compare comp ;
public:
myheap(){};
bool empty(){return data.empty() ;}
vector<T>::size_type size(){return data.size();} ;
void clear(){data.clear();} ;
void push(const T& x){
data.push_back(x);
push_heap(data.begin() , data.end() , comp) ;
}
const T& top(){
return *(data.begin()) ;
}
void pop(){
pop_heap(data.begin() , data.end() , comp) ;
data.pop_back() ;
}
} ;
二。测试该泛型堆
int a[] = {2,5,1,67,95,9,0,4,6} ;
int sz = sizeof(a) / sizeof(int) ;
int i;
myheap<int> h ;
h.clear() ;
for ( i = 0 ; i < sz ; i ++ ){
h.push(a[i]) ;
}
for ( i = 0 ; i < sz ; i ++ ) {
cout<<h.top()<<' ';
h.pop() ;
}
return 0 ;
输出:95 67 9 6 5 4 2 1 0
这里是STL堆算法默认的大顶堆。
做如下修改:
int a[] = {2,5,1,67,95,9,0,4,6} ;
int sz = sizeof(a) / sizeof(int) ;
int i;
myheap<int , greater<int> > h ;
h.clear() ;
for ( i = 0 ; i < sz ; i ++ ){
h.push(a[i]) ;
}
for ( i = 0 ; i < sz ; i ++ ) {
cout<<h.top()<<' ';
h.pop() ;
}
return 0 ;
输出:0 1 2 4 5 6 9 67 95
这一次就是小顶堆了。
- 堆函数
- 堆函数
- 堆函数
- 【堆】最小函数值
- 【堆】最小函数值
- 堆,栈,函数,alloca
- 堆排序 max_heapify 调整堆函数
- 内存相关函数(堆)
- 数据结构---堆及其相关函数
- 函数调用与栈、堆
- Windows 私有堆 - HeapCompact 函数
- 最大堆及其操作函数
- 系统构建堆的函数
- 函数调用栈与堆
- java实现最小堆(通过构造函数构造最小堆,相当于堆排序)
- 函数中堆内存写越界问题
- C++ 对数组堆排序的函数
- 《Windows核心编程》---堆管理函数
- ORACLE 如何产生一个随机数:DBMS_RANDOM
- 几个JSF流行名词的解释
- 动态调用带out参数的存储过程
- oracle随机数 — dbms_random
- n皇后问题——回溯算法
- 堆函数
- SNMP get
- 2009年科技论文统计结果 华科VS武大
- 我来喽!
- xxxxxxxxxxxxxx Start!
- MENU不能展开
- NSDictionary,NSArray,NSPredicate,JSON
- VS2005和VS2008设置默认浏览器
- 关于.net生成psd缩图的问题?