2013-09-21 105 views
-3

我正在嘗試使用庫函數make_heap構建分堆。請在類比較中指出錯誤。根元素應該是數組中的最小元素,但它不是。構建最小堆

#include<iostream> 
#include<map> 
#include<algorithm> 
using namespace std; 
class compare { 
     bool operator()(pair<int, int> lhs,pair<int, int> rhs) const 
     { 
      return lhs.second < rhs.second; 
     } 
    }; 
int main() 
{ 
    int arr[]={9,2,5,7,3,5,7,5,4,5,6,4,5}; 
    make_heap(arr,arr+13,compare); 
    cout<<arr[0]; 
} 
+2

什麼是 「它不工作」 是什麼意思?它做什麼,你期望它做什麼? –

+2

*「這不起作用」*不是問題描述。除了得出結論說它可能只是懶得工作,你不會得到更多的實質性內容。 – IInspectable

+0

我想建立一個使用lib fn max_heap的分鐘堆... plz建議某種方式。我迫切需要它。我是一個菜鳥。 – Anshul

回答

1

爲什麼在比較器中使用pair

用途:

class compare { 
public: //Make it public 
     bool operator()(const int &lhs, const int& rhs) const 
     { 
      return lhs < rhs; 
     } 

    }; 

然後

int arr[]={9,2,5,7,3,5,7,5,4,5,6,4,5}; 
make_heap(arr,arr+13,compare()); //Notice() 
for(auto i:arr) 
    cout<<i<<" "; 

HERE

+0

不需要通過ints作爲參考 - 這是矯枉過正。 –

+0

@EdHeal在什麼意義上矯枉過正? 我只是堅持'bool cmp(const Type1&a,const Type2 &b);'from [here](http://en.cppreference.com/w/cpp/algorithm/make_heap) – P0W

+0

你可以解釋我們怎麼樣使用比較器,我知道你在這裏做了什麼, – Anshul

2

嘗試

bool cmp(int l, int r) const 
    { 
     return l< r; 
    } 

即不在一個等級(如果你想使靜態

然後

make_heap(arr,arr+13,cmp);