简体   繁体   中英

Maintaining heap property of std::priority_queue

I am looking to create a max heap based on edge weights. However, when printing the heap, it is clear that it is not maintaining its binary heap property. How do I deal with this?

#include <iostream>
#include <cstring>
#include <sstream>
#include <fstream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <bitset>
#include <climits>
#include <ctime>
#include <algorithm>
#include <functional>
#include <stack>
#include <queue>
#include <list>
#include <deque>
#include <sys/time.h>
#include <iomanip>
#include <cstdarg>
#include <utility> //std::pair
#include <cassert>
using namespace std;


typedef struct{
        int u, v, weight;
    }edge;


class comparator{
public:
    bool operator()(const edge &e1, const edge &e2)
        {
            if(e1.weight<e2.weight)
                return true;
        }
};


void print_queue(priority_queue<edge, vector<edge> ,comparator> q)
{
    while(!q.empty())
        cout<<q.top().weight<<" ", q.pop();
    cout<<endl<<endl;
}

int main()
{

    priority_queue<edge, vector<edge> , comparator> q;
    edge e1={1,2,10};
    edge e2={1,3,23};
    edge e3={1,4,4};
    edge e4={1,5,99};
    edge e5={1,6,43};
    edge e6={1,7,29};

    q.push(e1);
    q.push(e2);
    q.push(e3);
    print_queue(q);
    q.push(e4);
    q.push(e5);
    q.push(e6);
    print_queue(q);
}

The bug is in your comparator function. I added "return false" in the case where e1.weight >= e2.weight:

    bool operator()(const edge &e1, const edge &e2)
    {
        if(e1.weight<e2.weight)
            return true;
        return false;
    }

and I think it now works the way you expect it to work:

Before:

[jsaxton@jsaxton-dev ~]$ ./a.out 4 23 10

29 23 4 10 43 99

After:

[jsaxton@jsaxton-dev ~]$ ./a.out 23 10 4

99 43 29 23 10 4

if(e1.weight<e2.weight)
       return true;

Okay what about else part ??

working fine with

else return false;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM