介面卡模式 實現優先順序佇列

2021-07-13 08:54:32 字數 1566 閱讀 1727

【介面卡模式】由於建立大堆和建立小堆方式相同,**相似,所以可以通過新增乙個比較器(利用compare,定義偽函式less和greater)實現大小資料的比較,防止大量**重複。

templatestruct less//小堆呼叫

};templatestruct greater//大堆呼叫

};templateclass compare>

class heap

;templateclass compare>

heap::heap()

:_a(null)

{}templateclass compare>

heap::heap(const t* a, size_t size)

//建大堆時,從下往上依次判斷並調整堆,使該結點的左右子樹都滿足大堆

for (int i = (int)(size - 2) / 2; i >= 0; --i)//不能定義為size_t(無符號)

//建小堆,類似建大堆的方式,從下向上進行調整堆,使該結點處的左右子樹都滿足小堆

//在進行調小堆時,也通過下調實現

}//下調--建大堆/小堆

templateclass compare>

void heap::_adjustdown(size_t parent)

if (com(_a[child], _a[parent]))//如果用greater時,為真,則表示子結點大於父親結點,進行交換

else

}}

優先順序佇列的實現利用堆實現

templateclass compare>

class priorityqueue//優先順序佇列---呼叫堆實現

void pop()

bool empty()

t& front()

t& tail()

size_t size()

void printpriority()

private:

heap_hp;

};

測試用例如下:

void test()

; priorityqueuehp;//大數優先順序高

hp.push(10);

hp.push(16);

hp.push(18);

hp.push(12);

hp.push(11);

hp.push(13);

hp.push(15);

hp.push(17);

hp.push(14);

hp.push(19);

hp.printpriority();

cout << "empty: " << hp.empty() << endl;

cout << "size: " << hp.size() << endl;

cout << "front: " << hp.front() << endl;

cout << "tail: " << hp.tail() << endl;

}

本文出自 「scen」 部落格,請務必保留此出處

C STL容器介面卡 棧 佇列 優先順序佇列

什麼是容器介面卡?容器介面卡 介面卡底層沒有自己的資料結構,它是另外乙個容器的封裝,它的方法全部由底層依賴的容器進行實現的 它沒有實現自己的迭代器,不能使用迭代器遍歷。來看這個例子 我們使用容器介面卡來實現乙個棧。template class stack void pop t top const p...

介面卡模式(類介面卡 物件介面卡)

做個筆記 引用 public inte ce usb public inte ce psp public class usber implements usb 類介面卡 psp適用usb介面 public class usbadapter extends usber implements psp 物...

介面卡模式 預設介面卡,類介面卡,物件介面卡

模式思想 改變乙個類的對外介面 增加或減少 以滿足不同外部呼叫者的需求 角色成員 目標介面 target 客戶所期待的介面。目標可以是具體的或抽象的類,也可以是介面。需要適配的類 adaptee 需要適配的類或適配者類。介面卡 adapter 通過包裝乙個需要適配的物件,把原介面轉換成目標介面。適配...