对于用户自定义的结构体,我了解到很容易实现。只需要重载运算符<即可。但是对于int/float等基本类型,我真的需要重载运算符<吗?以下是我的尝试:
#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应该可以解决问题。但是,你说不应该使用外部比较器?如果这不是正确的方法,那么通常达成这个目的的方式是什么?
int
的operator>=
,这不是一个严格弱序比较器,因此是非法的。 - ildjarnoperator> =
,但逻辑等价于operator <
或operator>
是可以的。请参阅这篇由现代C++之父之一撰写的出色文章,获取更多信息:Order I Say! - ildjarnstd::greater<int>()
。 - ildjarna == b
。那么a<b?false:true
是 true。这是错误的,根据 C++03 的 25.3/4 规定,比较器必须具有对于所有x
都满足!comp(x,x)
的属性。然而,b<a?true:false
是 false,所以这是正确的。 - Steve Jessop