C++ 维护std::priority_队列的堆属性

C++ 维护std::priority_队列的堆属性,c++,data-structures,stl,priority-queue,C++,Data Structures,Stl,Priority Queue,我希望创建一个基于边权重的最大堆。但是,当打印堆时,很明显它没有维护其二进制堆属性。我该怎么处理 #include <iostream> #include <cstring> #include <sstream> #include <fstream> #include <cstdlib> #include <cstdio> #include <cmath> #include <vector> #inc

我希望创建一个基于边权重的最大堆。但是,当打印堆时,很明显它没有维护其二进制堆属性。我该怎么处理

#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);
}

这个bug存在于比较器函数中。如果e1.weight>=e2.weight:

    bool operator()(const edge &e1, const edge &e2)
    {
        if(e1.weight<e2.weight)
            return true;
        return false;
    }
我认为它现在按照你期望的方式工作:

之前:

[jsaxton@jsaxton-开发~]$/a.out 42310

29234104399

之后:

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

99 43 29 23 10 4


这个bug存在于比较器函数中。如果e1.weight>=e2.weight:

    bool operator()(const edge &e1, const edge &e2)
    {
        if(e1.weight<e2.weight)
            return true;
        return false;
    }
我认为它现在按照你期望的方式工作:

之前:

[jsaxton@jsaxton-开发~]$/a.out 42310

29234104399

之后:

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

99 43 29 23 10 4


您是否使用了任何编译器警告?我可以在你的代码中看到五种不同的东西,甚至不用尝试。@KerrekSB我更新了工作代码。很好的代码可以展示给Doug Gregor。@Nemanjabric我希望我能给你不止一个upvote.ctime和cstdarg?您忘记了cuchar和future。您是否使用了任何编译器警告?我可以在你的代码中看到五种不同的东西,甚至不用尝试。@KerrekSB我更新了工作代码。很好的代码可以展示给Doug Gregor。@Nemanjabric我希望我能给你不止一个upvote.ctime和cstdarg?你忘记了cuchar和未来。换句话说,根本不需要if。只需使用return e1.weight bool operator()(const edge &e1, const edge &e2) { if(e1.weight<e2.weight) return true; return false; }