构建最小堆

时间:2013-09-21 16:58:35

标签: c++

我正在尝试使用库函数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 个答案:

答案 0 :(得分:2)

尝试

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

即。不在课堂上(如果你想让它静止

然后

make_heap(arr,arr+13,cmp);

答案 1 :(得分: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

相关问题