给定以下代码:
// range heap example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool Greater(int a, int b)
{
if (a > b)
{
return true;
}
else
{
return false;
}
}
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(), Greater);
cout << "initial min heap : " << v.front() << endl;
pop_heap (v.begin(),v.end(), Greater); v.pop_back();
cout << "min heap after pop : " << v.front() << endl;
v.push_back(9); push_heap (v.begin(),v.end(), Greater);
cout << "min heap after push: " << v.front() << endl;
sort_heap (v.begin(),v.end());
cout << "final sorted range :";
for (unsigned i=0; i<v.size(); i++) cout << " " << v[i];
cout << endl;
return 0;
}
为什么返回值如下:
initial min heap : 5
min heap after pop : 10
min heap after push: 9
final sorted range : 10 15 20 30 9 <= why I get this result, I expect 9 10 15 20 30.
如果我调用 sort_heap(v.begin(), v.end(), Greater),则返回值为30 20 15 10 9
.
问题 > 在这个示例中,我创建了一个最小堆。这就是我不能调用 sort_heap(v.begin(), v.end()) 的原因吗?
谢谢你