108次練習之堆的聲明及實現(二)

來源:互聯網
上載者:User

標籤:ack   visual   vector   for   bsp   max   測試   實現   name   

  昨天寫完堆的代碼後,今天又敲了一下,順便用到了函數對象,可以指定產生最小/大堆.

  (注釋就懶得寫了,有什麼問題可以私下留言,或者看我上篇文章,畢竟本文僅供個人娛樂)

/**檔案說明:堆的相關聲明及實現(第二遍)*作者:高小調*日期:2016-12-27*整合式開發環境:Microsoft Visual Studio 2010 */#include<vector>template<typename T>struct Min{bool operator()(T left,T right){return left<right;}};template<typename T>struct Max{bool operator()(T left,T right){return left>right;}};template<typename T,typename class Type = Min<T>>class Heap{public:Heap(){}Heap(T arr[],size_t sz):_a(arr,arr+sz){size_t LastNotLeapNode = (_a.size()-2)/2;for(int idx=LastNotLeapNode; idx>=0; --idx){_AdjustDown(idx);}}void Push(const T &e){_a.push_back(e);size_t LastNotLeapNode = (_a.size()-2)/2;_AdjustUp(LastNotLeapNode);}void Pop(){swap(_a[0],_a[_a.size()-1]);_a.pop_back();_AdjustDown(0);}protected:void _AdjustDown(size_t idx){size_t parent = idx;size_t child = idx*2+1;while(child<_a.size()){if(child+1<_a.size() && Type()(_a[child+1],_a[child])){++child;}if(Type()(_a[child],_a[parent])){swap(_a[child],_a[parent]);parent = child;child = parent*2+1;}else{break;}}}void _AdjustUp(size_t idx){size_t parent = idx;size_t child = 2*idx+1;while(child<_a.size() && child>parent){if(child+1<_a.size() && Type()(_a[child+1] , _a[child])){++child;}if(Type()(_a[child],_a[parent])){swap(_a[child],_a[parent]);child = parent;parent = (child-1)/2;}else{break;}}}private:vector<T> _a;};

 

/**檔案說明:測試檔案*作者:高小調*日期:2016-12-26*整合式開發環境:Microsoft Visual Studio 2010 */#include<iostream>using namespace std;#include"Heap2.h"void TestHeap(){int arr[] = {10,16,18,12,11,13,15,17,14,19};size_t sz = sizeof(arr)/sizeof(arr[0]);Heap<int> h1(arr,sz);//小堆Heap<int,Max<int>> h2(arr,sz);//大堆h1.Pop();h1.Push(5);h2.Pop();h2.Push(20);}int main(){TestHeap();return 0;}

   總結:

  第二遍再去敲堆的時候,就行雲流水多了,但還是犯了個小錯誤:在建構函式中,沒有給_a初始化...

  最基礎的,就是最精華的!

  繼續努力!

108次練習之堆的聲明及實現(二)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.