我在這篇部落格中介紹了二叉堆的c語言實現。
這次,我將使用c++模板類技術實現這個二叉堆,使它能夠儲存更多的資料型別。也就是c++中的通用容器(generic collection)概念。
改寫之後我們可以這樣建立乙個heap物件;
heaph;
在c實現中,必須傳遞乙個結構體例項的指標給函式,以便函式能夠操作結構體中的資料。但是,c++可以面相物件,函式可以炒作類中的私有成員變數(將原結構體中的資料成員設計成c++的私有成員)。原來固定不變的堆最大容量max_size也可以設計到類的成員變數中。
而c中初始化函式可以設計到c++的建構函式中。
c++類中沒有動態分配的變數,所以析構函式就不需要做什麼了。
c實現中的那些輔助函式可以設計成c++ heap類的私有成員函式。而巨集定義的函式,例如:
#define left_child(index) (2 * (index) + 1)
#define right_child(index) (2 * (index) + 2)
可以設計成inline函式,設計成內聯函式的好處就是可以對引數進行型別檢查。
下面是完整的實現**:
/*** this file implemente binary heap data structure
* using c++ template class
* generic collection
* * author by jianyong-lee
* 2014/11/13
* in southwest university
* * lisence :gpl
* */
#ifndef heap_template_h
#define heap_template_h
#include #include templateclass heap
inline int right_child(int index)
inline int parent(int index)
};templateheap::heap()
templateheap::~heap()
templatet heap::get_first_value()
t result;
result=values[0];
heap_size--;
if(heap_size!=0)
return result;
}templatevoid heap::add_value(t value)
values[heap_size]=value;
heap_size++;
if((heap_size-1)!=0)
}templatevoid heap::sift_down(int index)
if(rightchild>=heap_size)
for(i=0;i<32;i++)
{couths.add_value(s1);
hs.add_value(s2);
cout<
模板 二叉堆 優先佇列的二叉堆陣列實現
最近開始學資料結構,一直無心更新部落格,今天結束集訓,晚上打算碼一下最近的進度。建立乙個最大容量為maxsize的int型堆 maxheapque maxsize 預設最大容量為1007 maxheapque 作為優先佇列 pop 同優先佇列pop 如果佇列已為空還要執行pop,就會執行死迴圈以報錯...
二叉堆的c 實現
在下小白乙個 如有錯誤請指正 上 using system using system.collections.generic 資料結構 namespace datastructure 刪除 刪除的key public void remove t key 銷毀 public void destory ...
使用C 實現二叉堆
二叉堆可以用來實現優先佇列。二叉堆是一棵完全二叉樹,除了葉子節點那一層,其他的層都是滿的,葉子節點那一層是從左往右依次存放的,因此它們的父子元素的索引有數學公式可以參考,對於節點i來說,它的左兒子是2i,右兒子是2i 1,它的父親節點是i 2向下取整,因此,在其內部我們可以通過陣列來實現元素的儲存,...