新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
【數(shù)據(jù)結(jié)構(gòu)】優(yōu)先級隊列的實現(xiàn)(適配器模式)
代碼按照適配器模式實現(xiàn),若理解了堆的內(nèi)部怎么實現(xiàn)的,那優(yōu)先級的隊列實現(xiàn)則是非常簡單的了,堆的設計大家不明白的話,可以查看我的博客http://10740184.blog.51cto.com/10730184/1767076。
創(chuàng)新互聯(lián)是一家專注于成都網(wǎng)站制作、做網(wǎng)站與策劃設計,茂名網(wǎng)站建設哪家好?創(chuàng)新互聯(lián)做網(wǎng)站,專注于網(wǎng)站建設10余年,網(wǎng)設計領域的專業(yè)建站公司;建站業(yè)務涵蓋:茂名等地區(qū)。茂名做網(wǎng)站價格咨詢:13518219792
建立PriorityQueue.hpp:
#define _CRT_SECURE_NO_WARNINGS 1 #includeusing namespace std; #include #include template struct Less { bool operator() (const T& l, const T& r) { return l < r; } }; template struct Greater { bool operator() (const T& l, const T& r) { return l>r; } }; template class Compare=Less> class Heap { public: Heap() :_a(NULL) {} Heap(const T* a,size_t size) { for (int i = 0; i < size; i++) { _a.push_back(a[i]); } for (int i = (size - 2) / 2; i >= 0; i--) { _adjustDown(i); } } void _adjustDown(size_t parent) { Compare com; size_t child = 2 * parent + 1; size_t size = _a.size(); while (child com; while (child>0) { if (com(_a[child],_a[parent])) { swap(_a[parent], _a[child]); child = parent; parent = (child - 1) / 2; } else { break; } } } size_t Size() { size_t size = _a.size(); return size; } bool Empty() { assert(Size() >= 0); return Size() == 0; } void Pop() { assert(_a.Size() > 0); swap(_a[0], _a[Size - 1]); _a.pop_back(); _adjustDown(0); } T& GetTop() { return _a[0]; } void Print() { cout << "大堆序列:" << endl; for (int i = 0; i < _a.size(); i++) { cout << _a[i] << " "; } cout << endl; } public: vector _a; }; template class Compare = Less> class PriorityQueue { public: void Push(const T& x) { _hp.Push(x); } void Pop() { _hp.Pop(); } size_t Size() { return _hp.Size(); } bool Empty() { _hp.Empty(); } T& Top() { return _hp.GetTop(); } void Print() { _hp.Print(); } private: Heap _hp; };
建立PriorityQueue.cpp文件:
#define _CRT_SECURE_NO_WARNINGS 1 #pragma once #include "PriorityQueue.hpp" void Test() { int a[] = { 10, 11, 13, 12, 16, 18, 15, 17, 14, 19 }; PriorityQueuepq; pq.Push(10); pq.Push(11); pq.Push(13); pq.Push(12); pq.Push(16); pq.Push(18); pq.Push(15); pq.Push(17); pq.Push(14); pq.Push(19); pq.Print(); } int main() { Test(); system("pause"); return 0; }
名稱欄目:【數(shù)據(jù)結(jié)構(gòu)】優(yōu)先級隊列的實現(xiàn)(適配器模式)
網(wǎng)站地址:http://fisionsoft.com.cn/article/ipeidj.html