开发者

Why hasn't sort_heap put the elements in the order I expected?

Given the following code:

// 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;
}

why the return value is as follows:

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.

If I call sort_heap(v.begin(), v.end(), Greater), then return value is 30 20 15 10 9.

Question > In this sample, I create a min-heap. Is this the reason that I cannot call sort_heap(v.begi开发者_运维知识库n(), v.end())?

thank you


sort_heap only sorts the range if it is heap-ordered according to the provided comparator. Since you used Greater as the comparator in all the heap operations, you don't have the elements in heap order according to the default comparator, so sort_heap isn't guaranteed to work correctly. The regular sort algorithm should work just fine, though.


You need to pass Greater to sort_heap as with all the other heap operations.

sort_heap (v.begin(),v.end(), Greater);

As @Blastfurnace mentions, std::greater<int>() is preferable to defining your own function. Besides the elegance factor, there is a performance issue: when you pass a function by reference for implicit conversion to a functor, it is first implicitly converted to a function pointer, which can result in less efficient execution due to an indirect branch instruction.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜