堆函数

来源:互联网 发布:游戏运营数据分析 编辑:程序博客网 时间: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

这一次就是小顶堆了。

原创粉丝点击