優先順序佇列

2021-07-12 05:56:32 字數 1805 閱讀 1359

注:由於大堆與小堆的實現大同小異,只需要修改大於或小於號;所以為了**復用,本人使用了模板引數及模板的模板引數

模板的模板引數:為了引入仿函式即函式物件;此處不多介紹仿函式,它只是乙個函式物件;乙個型別;如下:

型別greatercompare與型別lesscompare:他們的內部都只是過載了();

template

struct greatercompare

};template

struct lesscompare};

堆的實現**如下:

#pragma once

#includeusing namespace std;

#include//仿函式(函式物件)

templatestruct greatercompare

};templatestruct lesscompare

};//模板型別的模板形參

templateclass compare = greatercompare> //預設引數

class heap

heap(const t* arr,int len)

//建堆:找第乙個非葉子結點的父親,然後向下調整

for (int i = len - 1; i >= 0; --i)

}//末尾增加乙個結點後,向上調整

void push(const t& x)

//刪除乙個結點時,先將堆頂資料與末尾資料交換,然後刪除末尾資料,最後向下調整

void pop()

t& size()

bool empty()

t& top()

void print()

cout << endl;

} ~heap()

{}protected:

//向下調整

void _adjustdown(int root)

if (com(_heaparr[child], _heaparr[root]))

else

} } //向上調整

void _adjustup(int child)

else

}}private:

vector_heaparr;

};//測試用例

void testheap()

; int len = sizeof(arr) / sizeof(arr[0]);

//大堆

heaphp1(arr, len);

hp1.print();

//小堆

heaphp(arr, len);

hp.print();

hp.push(21);

hp.print();

hp.pop();

hp.print();

}

測試結果如下圖:

優先順序佇列的實現就是對上面堆的一層封裝,**如下:

//將堆封裝成優先順序佇列

template class priorityqueue

~priorityqueue()

{} void queuepush(const t& x)

void queuepop()

bool queueempty()

int queuesize

t& queuefront()

private:

heap_heap;

};

佇列 優先順序佇列

優先順序佇列的隊尾是不需要改變的,永遠在低下標處。當佇列增加資料時,隊頭的位置就是資料項的大小減去1.public class priorityq 插入 public void insert long item else quearray j 1 item nitem 刪除 public long ...

優先順序佇列

分為最小優先順序佇列和最大優先順序佇列。優先順序佇列是一種用來維護一組元素構成的集合s的資料結構,這一組元素都有乙個關鍵字key,乙個最大優先順序佇列支援的操作 insert s,x 把x插入到集合s中 maxmum s 返回s中最大元素 extra max s 去掉s中最大關鍵字並返回該最大關鍵子...

優先順序佇列

1 include stdafx.h 2 include3 4 using namespace std 5 6 define max heap len 107 int heap max heap len 8 int heap size 0 the number of elements in heap...