stl priority_queue of C++ with struct

≯℡__Kan透↙ 提交于 2019-12-20 10:43:35

问题


How can we use STL priority_queue for struct ? Any illustration of pushing & popping , where struct has multiple data-types?
Say : struct thing { int a; char b;} glass[10]; .
Now how can i put this struct on priority_queue using 'int a' for ordering ?


回答1:


Here is a slightly modified answer to your original question, which you deleted for no apparent reason. The original contained enough information for you to figure this out, but here it goes: provide a less than comparison that uses the int for comparison.

All you need to do is provide a functor that implements a less-than comparison with strict weak ordering, or a less-than operator for your class implementing the same. This struct satisfies the requirements:

struct thing
{
    int a;
    char b;
    bool operator<(const thing& rhs) const
    {
        return a < rhs.a;
    }
};

then

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();



回答2:


Overload < operator for 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();



回答3:


You need to implement a compare function or overload operator to tell priority queue that on which order you want to sort your custom data. When priority queue will sort your data then it will need a way to know how to compare among them. You have to specify this by passing a function to priority queue or overloading operator in you custom data class or structure.

You can check this answer. This might help you. I have tried to explain multiple ways of using priority queue for custom data types.



来源:https://stackoverflow.com/questions/15601973/stl-priority-queue-of-c-with-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!