带有struct的C++的stl priority_queue

Man*_*rma 9 c++ struct priority-queue

我们如何将STL priority_queue用于struct?推送和弹出的任何插图,其中struct有多种数据类型?
说:struct thing { int a; char b;} glass[10];.
现在我如何使用'int a'将此结构放在priority_queue上进行排序?

jua*_*nza 25

这是对原始问题的略微修改的答案,您删除的原因没有明显.原始文件中包含足够的信息供您详细说明,但在这里:提供一个比使用int比较的比较.

您需要做的就是提供一个函数,它实现了与严格的弱排序的比较,或者实现相同的类的小于运算符.该结构满足要求:

struct thing
{
    int a;
    char b;
    bool operator<(const thing& rhs) const
    {
        return a < rhs.a;
    }
};
Run Code Online (Sandbox Code Playgroud)

然后

std::priority_queue<thing> q;
thing stuff = {42, 'x'};
q.push(stuff);
q.push(thing{4242, 'y'}); // C++11 only
q.emplace(424242, 'z'); // C++11 only    
thing otherStuff = q.top();
q.pop();
Run Code Online (Sandbox Code Playgroud)


mas*_*oud 5

的重载<运算符thing

struct thing
{
    int a;
    char b;

    bool operator<(const thing &o) const
    {
        return a < o.a;
    }
};

priority_queue<thing> pq;

thing t1, t2, t3;

// ...

pq.push(t1);
pq.push(t2);

// ...

t3 = pq.top();
pq.pop();
Run Code Online (Sandbox Code Playgroud)