据我所知,对于用户定义的结构,这很容易。只需重载运算符 <。但是,对于 int/float 等,我真的需要为 int 重载 operator < 吗? 这是我尝试过的:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool comp(const int& a, const int& b)
{
return a<b?false:true;
}
int main ()
{
int myints[] = {10,20,30,5,15};
vector<int> v(myints,myints+5);
vector<int>::iterator it;
make_heap(v.begin(), v.end(), comp);
cout << "initial min heap : " << v.front() << endl;
for (unsigned i=0; i<v.size(); i++) cout << " " << v[i];
cout<<endl;
pop_heap (v.begin(),v.end());
v.pop_back();
for (unsigned i=0; i<v.size(); i++) cout << " " << v[i];
cout<<endl;
}
结果是:
initial min heap : 5
5 10 30 20 15
30 10 15 20
现在 pop_heap,push_heap 不会正确维护最小堆?有没有更简单的方法来实现这一点? 谢谢!
编辑: 对不起,我没有仔细检查手册。是的,将 comp 传递给 pop_heap 或 push_heap 应该可以解决问题。但是,您是什么意思,我不应该使用外部比较器?如果这不是正确的方法,实现此目的的常用方法是什么?
最佳答案
使用 std::greater<int>()
作为比较器(对所有 make_heap
, push_heap
, pop_heap
)。 ()
很重要 - std::greater<int>
是一个仿函数类而不是一个函数,所以你需要一个它的实例。
关于c++ - 用 STL 维护最小堆的简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7681779/