C++中堆的使用及自定義類型排序

簡介

C++中堆(heap)是在vector的基礎上實現的。具體地,是定義了一些方法在vector類型數據上進行操作,包括
- make_heap 建立堆(默認最大堆)
- push_heap 加入元素
- pop_heap 刪除元素
- sort_heap 堆排序義的一些方法

代碼示例

#include<iostream>  
#include<vector>  
#include<algorithm>  

using namespace std;  

/* 自定義數據類型:包含一個整數、一個浮點數 */
typedef struct DoubleIndex
{
    int                 id;             // index
    double              val;            // value
    DoubleIndex(){}
    DoubleIndex(int _id, double _val): id(_id), val(_val){}
    /* 切記定義運算符重載 */
    bool operator < (const DoubleIndex &b) const { return val < b.val; }
    bool operator > (const DoubleIndex &b) const { return val > b.val; }
} DoubleIndex;

/* 比較函數 */
bool CompareDoubleIndex(const DoubleIndex &a, const DoubleIndex &b){
    return a.val < b.val;
}

int main()  
{  
    vector<DoubleIndex> list;
    vector<DoubleIndex>::iterator iter;

    /// 初始vector列表
    list.push_back(DoubleIndex(1, 3.1));
    list.push_back(DoubleIndex(2, 1.1));
    list.push_back(DoubleIndex(3, 4.1));
    list.push_back(DoubleIndex(4, 2.1));
    list.push_back(DoubleIndex(5, 0.1));

    /// 建立堆,make_heap這一步將上面的列表構造成一個堆
    make_heap(list.begin(), list.end(), CompareDoubleIndex);
    for(iter=list.begin();iter!=list.end();++iter)  
        cout<<(*iter).id << ":" << (*iter).val<<endl;  
    cout<<endl;
    /* 初始堆
    3:4.1
    4:2.1
    1:3.1
    2:1.1
    5:0.1
    */

    /// 加入元素第一步:新元素壓入vector列表
    list.push_back(DoubleIndex(6,10.1));
    for(iter=list.begin();iter!=list.end();++iter)  
        cout<<(*iter).id << ":" << (*iter).val<<endl;  
    cout<<endl; 
    /* 這是加入vector的效果,可以看到,新元素被放在了列表末尾
    3:4.1
    4:2.1
    1:3.1
    2:1.1
    5:0.1
    6:3.65  
    */
    // 加入元素第二步:新元素加入堆
    push_heap(list.begin(), list.end());
    for(iter=list.begin();iter!=list.end();++iter)  
        cout<<(*iter).id << ":" << (*iter).val<<endl;  
    cout<<endl; 
    /* 可以看到,新元素[6:3.65]更新了原先第二層右邊的節點[1:3.1]
    3:4.1
    4:2.1
    6:3.65
    2:1.1
    5:0.1
    1:3.1
    */

    /// 堆排序
    sort_heap(list.begin(), list.end());
    for(iter=list.begin();iter!=list.end();++iter)  
        cout<<(*iter).id << ":" << (*iter).val<<endl;  
    cout<<endl;  
    /*
    5:0.1
    2:1.1
    4:2.1
    1:3.1
    6:3.65
    3:4.1
    */

    return 0;  
}  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章