C 實現最小堆(binary heap)

2021-06-12 23:50:15 字數 1410 閱讀 9265

閒來無事,用c++實現了最小堆。

用到了模板類泛型程式設計,用陣列實現的最小堆。

binheap.h中的宣告:

templateclass binheap

;

其中capacity是堆的容量,在數值上等於count -1,因為堆的根從陣列elements[1]開始,elements[0]留著,用作標記。

下面是全部**:

binheap.h

#pragma once

#include using std::runtime_error;

#define count 21

#define min 0

templateclass binheap

;templatebinheap::binheap(void):capacity(count-1),size(0)

templatebinheap::~binheap(void)

templatevoid binheap::makeempty()

templateint binheap::isfull()

templatetype binheap::findmin()

return null;

}templatevoid binheap::insert(const type& x)

else

elements[tmpsize] = x; }}

templatevoid binheap::deletemin()

else

else

}elements[i] = lastelement;

}}

binheap.cpp 中是空的,就包含兩個最基本的include。原因後面解釋。

測試**:

// minheap.cpp : 定義控制台應用程式的入口點。

//#include "stdafx.h"

#include "binheap.h"

#include using std::cout;

using std::endl;

int _tmain(int argc, _tchar* argv)

cout<<"the min element is "<

解釋一下為什麼把成員函式的定義也放到了標頭檔案中:

因為本**用的是模板類程式設計,而當下很多編譯器都不再支援模板類程式設計的宣告和實現分開。即 如果把函式實現放在cpp檔案裡,用main函式測試的時候會出現提示

public: __thiscall binheap::binheap(void)" (??1?$compare@h@@qae@xz) 無法進行初始化。

也許很久以前是支援的,但是至少vs2008和vs2010是不支援的。

所以只能把成員函式的實現也放到標頭檔案裡,就ok了~

C 最小堆實現

mini heap.h pragma once include template class mini heap node heap 最小堆 uint32 t max size 最大儲存數 uint32 t size 儲存數 擴容 void expansion 刪除指定下標節點 void del n...

最小堆的實現

這邊實現的是最小堆,最小堆是這樣定義的,首先堆是一棵完全二叉樹,每乙個節點都有乙個權值,滿足的條件是,父節點的權值總是大於等於子節點的權值 include using namespace std 最小堆類的定義如下 template class minheap template void minhe...

最小堆 C 模板

本人對最小堆的理解,相關注釋在 中 include using namespace std const int maxn 10000000 int h maxn 用乙個一維陣列模擬最小堆,父節點的的值小於子節點的值 int n 用來記錄堆的元素的個數 void swap int x,int y 向下...